I’m trying to initialize an array in a parent structure from its children. I currently have the solution below, however the two useEffect calls overwrite each other, and the output of errors
is "{"2":0}", where I want it to be "{"1":0, "2":0}.
I don’t want to initialize errors
in the Parent structure as I would need to write multiple twice the same code for initialization (I optimally would only append the new child structures and the error array should be changed). Is it possible to do?
Thanks.
Parent.js:
export default function Parent(props){
const [errors, setErrors] = React.useState({});
return <React.Component>
<Child errors=errors setErrors=setErrors identifier="1"/>
<Child errors=errors setErrors=setErrors identifier="2"/>
{JSON.stringify(errors)}
</React.Component>
}
Child.js:
export default function Child(props){
useEffect(() => {
props.setErrors({...props.errors, [props.identifier]:0});
}, []);
return <React.Component>
</React.Component>
}
2
Answers
You should use the callback for setting the state in this case:
Child.js:
You can pass a function to
setErrors
to update the value given the previous state.See the documentation for
set
functions fromuseState
: