uiwjs / react-codemirror

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

onChange handler should not fire when props change #310

Open PvanHengel opened 2 years ago

PvanHengel commented 2 years ago

Hi, I am having an issue when trying to update some props from elsewhere in the app, that impact the value prop for CodeMirror. See the code below. There is a rather lengthy discussion on another wrapper here (https://github.com/scniro/react-codemirror2/issues/29) that somewhat describes this issue. Wondering if you had a clean work around, or way we can handle this in the component vs outside?

const Test = () => {

    const [state, setState] = useState({
        test:"value",
        editorValue:"Placeholder"
    })

    const changeState = () => {
        setState({test:"updated value", editorValue:"Updated Placeholder"})
    }

    return (
        <>
        <button onClick={changeState}>Change State</button>
        <CodeMirror
            value={state.editorValue}
            height="75vh"
            extensions={[xml({ jsx: true })]}
            onChange={(value, viewUpdate) => {
                setState({...state, editorValue: value )
            }}
        />
        <div>{JSON.stringify(state)}</div>
        </>
    )
}

export default Test
jaywcjlove commented 2 years ago

@PvanHengel This is an CodeMirror internal method that listens for changes to the view. I see your value has changed, which should fire the onChange event.

https://github.com/uiwjs/react-codemirror/blob/22cc81971a532c04fbf22565d725db60a191c259/src/useCodeMirror.ts#L49-L55