editor.js icon indicating copy to clipboard operation
editor.js copied to clipboard

Strange behavior when accessing state value in onChange

Open apisit opened this issue 1 year ago • 0 comments

I get this strange behavior when I am trying to access a state value in onChange — it always return the original value that is set with useState

Vite + React

Please see the video here.

https://github.com/codex-team/editor.js/assets/1012916/bdbd470b-3944-4be2-a28b-044d5c541cad

Anyone have any idea what causes this?

Code

import React, { useRef } from 'react'
import EditorJS from '@editorjs/editorjs';
function App() {

  const ref = useRef(null);
  const [title, setTitle] = React.useState("this is a title")
  const [detail, setDetail] = React.useState({})

  const onChange = async (api, event) => {
    console.log("title is ", title)
    const content = await ref.current.saver.save()
    setDetail(content)
  }

  React.useEffect(() => {
    if (!ref.current) {

      const editor = new EditorJS({
        holder: "editorjs",
        onReady: () => {
          console.log("onReady")
          ref.current = editor
        },
        data: detail,
        logLevel: "ERROR",
        tools: {

        },
        onChange: onChange
      });
    }

  }, [])

  return (
    <>
      <input type="text" value={title} onChange={(e) => { setTitle(e.target.value) }} />
      <button onClick={(e) => { alert(title) }}>Title is</button>
      <div id="editorjs"></div>
      {title}
    </>
  )
}

export default App

apisit avatar Dec 16 '23 14:12 apisit