Home > Back-end >  React state value is lost when there are multiple children elements
React state value is lost when there are multiple children elements

Time:01-10

I'm trying to maintain a state in parent that contains the statuses of the children. I'm updating the status from each child individually in a useEffect. But I'm only getting the status of the last child and not the rest. I think it's because of some asynchronous execution. Does anyone have an idea of how to get the status of all the children and update in parent? I have the sample code in https://codesandbox.io/s/fervent-cohen-dspwll?file=/src/App.js

Please check the console. The update I'm doing from Child1 is lost.

CodePudding user response:

You should not set a new state by relying in stale state if you can avoid it. The correct way to update a state in this case is

setStatus(oldStatus => ({ ...oldStatus, [order]: state }));
  • Related