uiwjs / react-codemirror

CodeMirror 6 component for React. @codemirror https://uiwjs.github.io/react-codemirror/
https://uiwjs.github.io/react-codemirror/
MIT License
1.65k stars 132 forks source link

State is not updated #193

Closed Pitel closed 3 years ago

Pitel commented 3 years ago

Reading the state.doc returned from useCodeMirror always returns an empty document, even when I write something in the editor!

Screenshot

jaywcjlove commented 3 years ago

Example

@Pitel Example: https://codesandbox.io/embed/react-codemirror-example-codemirror-6-hook-state-is-not-updated-193-hbj1d?fontsize=14&hidenavigation=1&theme=dark

import { useEffect, useRef } from "react";
import { useCodeMirror } from "@uiw/react-codemirror";
import { javascript } from "@codemirror/lang-javascript";

const code = "console.log('hello world!');\n\n\n";

export default function App() {
  const editor = useRef();
  const { view, setContainer } = useCodeMirror({
    container: editor.current,
    extensions: [javascript()],
    value: code
  });
  useEffect(() => {
    if (editor.current) {
      setContainer(editor.current);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [editor.current]);
  function handle() {
    console.log(">>>>", view.viewState.state.doc);
  }
  return (
    <div>
      <button type="button" onClick={() => handle()}>
        Button
      </button>
      <div ref={editor} />
    </div>
  );
}
Pitel commented 3 years ago

Oh, so the state is just the inital state, and current state is accessed throug view. Got it. :+1: