react-md-editor icon indicating copy to clipboard operation
react-md-editor copied to clipboard

onChange function is cached

Open avalero opened this issue 3 years ago • 6 comments

The onChange prop function of the MDEditor component is cached (due to the useReducer), and thus data passed is taken as closure, not updating when component re-renders.

For example, for this code

const [data, setData] = useState({text: "", number:0})
<MDEditor
    onChange={(text) => setData({...data, text});
    // ....
/>

Problem happens if I update number --> setData({...data, number: 5}) When MDEditor changes, number is reset to 0, because onChange function is cached with data being {text:"", value: 0}

I hope I have made myself clear. If not I can push a full component example of this problem.

avalero avatar Nov 23 '21 18:11 avalero

I have the same problem.

eleven-huang avatar Nov 24 '21 05:11 eleven-huang

@avalero Can you provide a complete example?

jaywcjlove avatar Nov 26 '21 10:11 jaywcjlove

Hello @jaywcjlove , yes, this is a working Component that shows this behaviour

const Example: FC = () => {
  const [data, setData] = useState<{ text: string; number: number }>({
    text: "",
    number: 0,
  });

  return (
    <div>
      <input
        type="number"
        value={data.number}
        onChange={(e) => setData({ ...data, number: Number(e.target.value) })}
      />
      <MDEditor
        value={data.text}
        onChange={(value) => setData({ ...data, text: value as string })}
      />
    </div>
  );
};

Whenever I write on the MDEditor data.number resets to 0, because data is cached on the onChange function with its initial value number:0

avalero avatar Nov 26 '21 11:11 avalero

@avalero @eleven-huang I think this problem is solved perfectly.

jaywcjlove avatar Nov 26 '21 12:11 jaywcjlove

Great @jaywcjlove , thanks for your time and effort!!

avalero avatar Nov 26 '21 12:11 avalero

Great work @jaywcjlove

eleven-huang avatar Nov 28 '21 14:11 eleven-huang