1

I am not able to update my context object from child component. Here is my provider file for creating react context and that component is wrapped over whole application in root app.tsx file.

I can fetch context in child components but I am not sure how to update it.

const CorporateContext = React.createContext(undefined);

export const useCorporateContext = () => {
    return useContext(CorporateContext);
};

export const CorporateProvider = ({ children }) => {
  const [corporateUserData, setCorporateUserData] = useState(undefined);

  useEffect(() => {
      const localStorageSet = !!localStorage.getItem('corporateDetailsSet');

      if (localStorageSet) {
          setCorporateUserData({corporateId: localStorage.getItem('corporateId'), corporateRole: localStorage.getItem('corporateRole'), corporateAdmin: localStorage.getItem('corporateAdmin'), corporateSuperAdmin: localStorage.getItem('corporateSuperAdmin')});
      } else {
          (async () => {
              try {
                  const json = await 
                  fetchCorporateUserDetails(getClientSideJwtTokenCookie());

                  if (json.success !== true) {
                      console.log('json invalid');
                      return;
                  }

                  setCorporateUserData({corporateId: json.data.corporate_id, corporateRole: json.data.corporate_role, corporateAdmin: json.data.corporate_role == 'Admin', corporateSuperAdmin: json.data.corporate_super_admin});
                  addCorporateDetailsToLocalStorage(corporateUserData);
              } catch (e) {
                  console.log(e.message);
              }
          })();
      }
  }, []);

  return (
      <CorporateContext.Provider value={corporateUserData}>
            {children}
      </CorporateContext.Provider>
  );
};

export default CorporateProvider;

Update: Here is what I changed and context seems to be updated (at least it looks updated when I check in chrome devtools) but child components are not re-rendered and everything still stays the same:

I changed react context to:

const CorporateContext = React.createContext({
    corporateContext: undefined,
    setCorporateContext: (corporateContext) => {}
});

Changed useState hook in a component:

  const [corporateContext, setCorporateContext] = useState(undefined);

Passed setState as property to context:

        <CorporateContext.Provider value={{corporateContext , setCorporateContext}}>
        {children}
    </CorporateContext.Provider>
Denis2310
  • 939
  • 1
  • 15
  • 41
  • Does this answer your question? [How to update React Context from inside a child component?](https://stackoverflow.com/questions/41030361/how-to-update-react-context-from-inside-a-child-component) – vsync Dec 14 '22 at 17:53

2 Answers2

1

You can also pass in setCorporateUserData as a second value to the provider component as such:

//...
return (
      <CorporateContext.Provider value={{corporateUserData, setCorporateUserData}}>
            {children}
      </CorporateContext.Provider>
  );

You can then destructure it off anytime you want using the useContext hook.

  • I tried it and if I check react tools extension that I have in browser, context is updated but child components are not re-rendered so basically nothing changes – Denis2310 Oct 05 '21 at 09:03
  • Please check my edited answer. I did it but child components are not re-rendered – Denis2310 Oct 05 '21 at 09:07
  • I don't think there's a need to change the context format. And did you try using the setCorporateUserData in the child component? – Uchechukwu Nwafor Oct 05 '21 at 09:30
  • i tried using this and context is changes when I check that component in devtools but content is not rerendered. can useEffect() hook in that context file maybe cause problems? – Denis2310 Oct 05 '21 at 09:33
  • Looking at what you did, I don't think I can spot any error here. maybe [this](https://blog.uchechukwunwafor.codes/react-context-api-explained-ckk6gzs07040jics18jy00v0a) would help? – Uchechukwu Nwafor Oct 05 '21 at 21:47
  • Thanks for help! Check my answer below how I resolved it. – Denis2310 Oct 06 '21 at 11:20
0

How I resolved this issue:

Problem was that I have cloned corporateContext object and changed property on that cloned object and then I passed it to setCorporateContext() method. As a result of that, context was updated but react didnt noticed that change and child components were not updated.

let newCorporateContext = corporateContext;
newCorporateContext.property = newValue;
setCorporateContext(newCorporateContext);

After that I used javascript spread operator to change the property of corporateContext inside setCorporateContext() method.

setCorporateContext({...corporateContext, property: newValue);

After that, react noticed change in hook and child components are rerendered!

Denis2310
  • 939
  • 1
  • 15
  • 41