Multiple children not passing state back to context (only last elemet does)

Viewed 42

https://codesandbox.io/s/purple-violet-ci3vdv?file=/src/App.js

I want a way to keep a log of the state of all child element's state so have tried to use a context provider to house this information.

The context provider and exposes its setState function to its consumers. Then I am updating the context's state in the useEffect of the child prop.

But you will see on the link above that on first render the state of the context only shows one item (the last), but when any button is clicked the state of the clicked consumer will update to the contexts state?

My goal is for the all objects to be displayed on the page after the first render.

Its easier to show the minimal working example in the code above.

EDIT: tried so many things to make this work - should be be using something like Recoil to make it work as expected?

2 Answers

Try using this inside mergeState:

setDrags((ps) => ({ ...ps, ...childState }));

If you call mergeState by multiple components consecutively, when one updates state, and then another component also calls it, the drags which you were spreading before, hasn't been updated yet, hence you need updater function in setState which will give you previous state.

Related