lexical icon indicating copy to clipboard operation
lexical copied to clipboard

Bug: UpdateListener with debounce

Open Julhol-droid opened this issue 2 years ago • 3 comments

Hello I want to update some state, whenever the editor receive an update. However i want to include a debounce function to delay the state change by a bit for performance reasons.


function debounce<T extends Function>(cb: T, wait = 300) {
  let h: ReturnType<typeof setTimeout>

  let callable = (...args: any) => {
    clearTimeout(h)
    h = setTimeout(() => cb(...args), wait)
  }

  return <T>(<any>callable)
}


 const [editor] = useLexicalComposerContext()

useEffect(() => {
    editor.registerUpdateListener(({ editorState }) => {
      console.log('update detected')
      debounce(() => {
        console.log('Should update in debonuce function')
      }, 500)
    })
  }, [editor])

Lexical version: 0.13.1 Lexical/react: 0.13.1

Steps To Reproduce

The current behavior

The console log insided my debounce function doesnt get called ever.

The expected behavior

The console log should be called

Julhol-droid avatar Feb 20 '24 16:02 Julhol-droid

Try this:

  const [editor] = useLexicalComposerContext();

  const debounced = debounce(() => {
    console.log('Should update in debounce function');
  }, 500);

  useEffect(() => { 
    return editor.registerUpdateListener(({ editorState }) => {
      console.log('update detected');
      debounced();
    });
  }, [editor, debounced]);

or

  const [editor] = useLexicalComposerContext();

  useEffect(() => {
    const debounced = debounce(() => {
      console.log('Should update in debounce function');
    }, 500);

    return editor.registerUpdateListener(({ editorState }) => {
      console.log('update detected');
      debounced();
    });
  }, [editor]);

The way I see it:

  1. You have to call the returned callable function. you were not calling it.
      debounce(() => {
        console.log('Should update in debonuce function')
      }, 500)() // <- you forgot to call it
    
  2. Every update should call same callable closure. So, call debounce outside of updateListener callback and just use the returned callable
  3. regitserUpdateListener returns cleaner. You can utilize it by put return in front of it in useEffect, otherwise you would see duplicative events in certain cases (i.e. react dev mode).

2wheeh avatar Feb 20 '24 16:02 2wheeh

BTW, this kind of question will be more welcomed and easy to get answered in discussion or discord community 😋

2wheeh avatar Feb 20 '24 17:02 2wheeh

Thank you very much. Yes this i was missing. Cool I will join Discord.

Julhol-droid avatar Feb 21 '24 10:02 Julhol-droid