Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

onChange function is cached #297

Open
avalero opened this issue Nov 23, 2021 · 6 comments
Open

onChange function is cached #297

avalero opened this issue Nov 23, 2021 · 6 comments

Comments

@avalero
Copy link
Contributor

avalero commented Nov 23, 2021

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.

@eleven-huang
Copy link

I have the same problem.

@jaywcjlove
Copy link
Member

@avalero Can you provide a complete example?

@avalero
Copy link
Contributor Author

avalero commented Nov 26, 2021

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

jaywcjlove added a commit that referenced this issue Nov 26, 2021
jaywcjlove added a commit that referenced this issue Nov 26, 2021
@jaywcjlove
Copy link
Member

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

@avalero
Copy link
Contributor Author

avalero commented Nov 26, 2021

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

@eleven-huang
Copy link

Great work @jaywcjlove

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants