0

I have an uncontrolled child component and I'm running into trouble making the save feature. (sadly, I could not find any way to make it controlled; it is a text box made by using a crude content-editable workaround, which is the best I could do for my case).

Parent

const [text, setText] = useState('');
const save = () => {
    makeAPICall(text);
};
...
return <Child initialText={text} setText={setText} save={save} />

Child

handleClick = () => {
    props.setText(myText)
    props.save();
};

The problem is that the text in Parent is not immediately updated, so it calls Parent's save with the old state. I want to run save next render with updated text in Parent. Is this possible?

Currently, my workaround is I have a saveFlag and useEffect(..., [saveFlag]), but it might become very confusing later and I'm wondering if there is something better.

Joe C.
  • 397
  • 4
  • 15

2 Answers2

0

You can/should use useEffect hook instead of having another save function. It will run "after" each text change as a callback.

const [text, setText] = useState('');

useEffect(() => {
    makeAPICall(text);
}, [text]);

return <Child initialText={text} setText={setText} />

Check out this.

codemode
  • 478
  • 3
  • 11
0

Maybe you could just pass the text by function parameters:

Parent

const save = (text) => {
    makeAPICall(text);
};

Child

handleClick = () => {
    props.setText(myText)
    props.save(myText);
};
leo
  • 156
  • 3