lexical
lexical copied to clipboard
Bug: UpdateListener with debounce
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
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:
- You have to call the returned
callablefunction. you were not calling it.debounce(() => { console.log('Should update in debonuce function') }, 500)() // <- you forgot to call it - Every update should call same
callableclosure. So, calldebounceoutside of updateListener callback and just use the returnedcallable regitserUpdateListenerreturns cleaner. You can utilize it by putreturnin front of it inuseEffect, otherwise you would see duplicative events in certain cases (i.e. react dev mode).
BTW, this kind of question will be more welcomed and easy to get answered in discussion or discord community 😋
Thank you very much. Yes this i was missing. Cool I will join Discord.