skip to Main Content

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


  1. You should use the callback for setting the state in this case:

    Child.js:

    export default function Child(props){
        useEffect(() => {
            props.setErrors((previousErrors)=> {...previousErrors, [props.identifier]:0});
        }, []);
       return <React.Component>
              </React.Component>
    }
    
    Login or Signup to reply.
  2. You can pass a function to setErrors to update the value given the previous state.

    props.setErrors(prev => ({...prev, [props.identifier]: 0}));
    

    See the documentation for set functions from useState:

    If you pass a function as nextState, it will be treated as an updater function. It must be pure, should take the pending state as its only argument, and should return the next state. React will put your updater function in a queue and re-render your component. During the next render, React will calculate the next state by applying all of the queued updaters to the previous state.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search