react-codemirror2 icon indicating copy to clipboard operation
react-codemirror2 copied to clipboard

Component prop updates are ignored

Open andyrichardson opened this issue 6 years ago • 9 comments

Currently, component updates are being ignored

/** @internal */
public shouldComponentUpdate(nextProps, nextState) {
  return !SERVER_RENDERED
}

This means that any update to event handlers just straight up don't work.

In this example, regardless of any calls to setValue, whenever a key is pressed, only the first function passed to CodeMirror is called.

const component = () => {
  const [value, setValue] = useState("old value");
 
  const handleKeyPress = () => {
    console.log("key pressed - value is", value);
  }

  useEffect(() => {
    setValue("new value")
  }, []);

  // ...
  onKeyPress={handleKeyPress} // The new function is ignored on second render
  // ...
}

Edit: Looks like the issue in this case is due to the way SSR is being detected - I'm trying to use this inside a chrome devtools extension.

Edit 2: Nothing to do with a chrome extension... I've created a PR :+1:

andyrichardson avatar Jun 21 '19 15:06 andyrichardson

I ran into this with onBlur as well. This works if you point to an unchanging function reference (i.e.: class-based components with bound function handlers), but does not work with hooks that have ever-changing function references.

mhuggins avatar Dec 11 '19 21:12 mhuggins

There may be a solution that involves useRef for the callback function, but I didn't pursue it too deeply since switching to a class based component resolved it for me.

mhuggins avatar Dec 11 '19 21:12 mhuggins

@andyrichardson @mhuggins I am a lot shorter on time these days as when I started this project. Codemirror & React APIs are moving to quickly for me to keep atop of for the day-to-day. I am looking for a co-maintainer of this project. Please contact me directly if you are interested. Thank you for understanding.

scniro avatar Jan 19 '20 16:01 scniro

Problem is still here 2 years after. Someone is looking for a solution ?

paztis avatar Jan 27 '21 14:01 paztis

I've found a way by adding a key on the <CodeMirror> tag to force reload on props change

paztis avatar Jan 27 '21 15:01 paztis

@paztis did you find a solution? Can this be done with useRef in a functional component?

ChristopherHButler avatar Mar 08 '21 18:03 ChristopherHButler

I add a key to the react component, and the key is equal to the code value. Like this, when the input code change, the component rendering is forced

paztis avatar Mar 08 '21 18:03 paztis

Ahhh ok thanks

ChristopherHButler avatar Mar 08 '21 19:03 ChristopherHButler

@paztis but after type in=> code change => cm re-render => the cursor disappear, how did you solve it? thanks

hhhluke avatar Aug 20 '21 03:08 hhhluke