Search code examples
reactjsdebouncingtiptap

How to use debounce with Tiptap


I am using Next in the frontend, convex in the backend to build a text editor. Till now, I have made it so that when there is any update in the editor, I am updating the updated content to the database with mutations. But the problem arises when I try to add debounce to it, since I wouldn't want the database to be updated with each keyPress, so I implemented this

const debounce = require("lodash.debounce");

  const editor = useEditor({
    extensions: [StarterKit],
    onUpdate: debounce(({ editor }: { editor: any }) => {
      updateContent({
        documentId: document?.[0]?._id as Id<"aipen">,
        content: editor?.getHTML(),
      });
    }, 2000),
  });

It should only call the updateContent when there is a gap of 2000 ms between two keyPress, but it is rather calling it on every keyPress or update in the editor.

How can I fix this?


Solution

  • I think you just need to assign the debounced function to a variable on the top level:

    const debounce = require("lodash.debounce");
    
    const debouncedOnUpdate = debounce(({ editor }: { editor: any }) => {
        updateContent({
            documentId: document?.[0]?._id as Id<"aipen">,
            content: editor?.getHTML(),
        });
    }, 2000);
    
    const editor = useEditor({
        extensions: [StarterKit],
        onUpdate: debouncedOnUpdate,
    });
    
    

    Otherwise debounce has no way to keep a state that can keep track of the time.