react-md-editor
react-md-editor copied to clipboard
onChange function is cached
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.
I have the same problem.
@avalero Can you provide a complete example?
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 @eleven-huang I think this problem is solved perfectly.
Great @jaywcjlove , thanks for your time and effort!!
Great work @jaywcjlove