Search code examples
reactjsreact-hooksreact-context

Get previous state and update context object indirectly


I am currently referring to a context object and updating in my child component as below:

setMyContextObjectData(prevState => {
    return {
        myGroupOrder: {...prevState.myGroupOrder},
        myGroups: {
        ...prevState.myGroups,
        'Section 1': myData.myGroups['Section 1']
        }
    };
});

Now there are multiple child components which are updating this context object.

If I want to not update this context object directly in my child components, but instead want to pass the information to parent component (via props) and update the context object only in my parent component, can I use a local state in my child component and update that? If yes, how can I get the "prevState" for "myContextObjectData"?


Solution

  • // Parent

     const updateFromChild = (dataFromChild) => {
        setMyContextObjectData((prevState) => {
          return {
            ...prevState,
            ...dataFromChild,
          };
        });
      };
      <Child onUpdate={updateFromChild} />
    

    // Child

     onUpdate({
        myGroupOrder: {// new data},
        myGroups: {
          'Section 1': {// new data},
        },
      });