TypeCellOS / BlockNote

A React Rich Text Editor that's block-based (Notion style) and extensible. Built on top of Prosemirror and Tiptap.

Home Page:https://www.blocknotejs.org/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Onchange not been correctly fired

messaddek opened this issue · comments

Describe the bug
The content change not immediately propagated through OnChange.
I want to implement the preview of the written text : here the code i used:

To Reproduce
add an onChange as prop in the host component :

onChange?: (value: string) => void; // props

Methods declaration:

const saveToStorage = useCallback((jsonBlocks: Block[]) => {
      return () => {
        if (onChange) {
          console.log(jsonBlocks);
          setTimeout(() => {
            onChange(JSON.stringify(jsonBlocks));
          }, 1000);
        }
      };
    }, []);

Returns:

<BlockNoteView
    editable={editable}
    onChange={saveToStorage(editor.document)}
    editor={editor}
    theme={resolvedTheme === "dark" ? "dark" : "light"}
  />    

In the target component :

 <FormControl>
      <Editor
          initialContent={field.value}
          onChange={(content) => {
              updateContent(content);
          }}
      />
 </FormControl>

Where :

const updateContent = useCallback((value: string) => {
    form.setValue("content", value);
}, []);

Misc

  • Node version:
  • Package manager: npm
  • Browser: Chrome
  • I'm a sponsor and would appreciate if you could look into this sooner than later 💖

What is if (onChange) { in your snippet? afaik the onChange handler should work ok. Closing this, but feel free to add a reproducible (stackblitz) example

The ? is used to prevent an execution of nonPassed arg.

https://stackblitz.com/edit/nextjs-b3unwj

You're calling editor.document at render time. Try this:

 const saveToStorage = useCallback(() => {
    console.log(editor.document);
    if (onChange) {
      setTimeout(() => {
        onChange(JSON.stringify(editor.document));
      }, 1000);
    }
  }, [editor]);

You're calling editor.document at render time. Try this:

 const saveToStorage = useCallback(() => {
    console.log(editor.document);
    if (onChange) {
      setTimeout(() => {
        onChange(JSON.stringify(editor.document));
      }, 1000);
    }
  }, [editor]);

It works, thanks !