Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJs Context not updated, values always default

  • I have parent wrapper component and I added react context inside it.
  • Inside that wrapper component I also have useEffect() hook which I use to fetch some values from API and then set these values to context.
  • Inside my child component which is using context, values for context are always default ones. When I check in browser react tools it seems that values for context are updated but when I test it with console.log it always returns default ones.

Parent component which has context inside:

...
export const CorporateContext = createContext({corporateId: null, corporateRole: null, corporateAdmin: null, corporateSuperAdmin: null});

export const CorporateWrapper = ({ apiBaseUrl, children }) => {
    const [corporateContextDefaults, setCorporateContextDefaults] = 
    useState({corporateId: null, corporateRole: null, corporateAdmin: null, corporateSuperAdmin: null});

    useEffect(() => {
        (async () => {
            try {
                const json = await fetchCorporateUserDetails(apiBaseUrl);

                if (json.success !== true) {
                    console.log(json.message);
                  } else {
                    console.log(json.data) // <-- TESTED RESPONSE FROM API
                    setCorporateContextDefaults(json.data); // <-- UPDATE CONTEXT VALUES HOOK AND PASS IT BELOW TO CONTEXT PROVIDER
                  }

               
                } catch (e) {
                    console.log(e.message);
                }
            })();
    }, []);

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

export default CorporateWrapper;

Child component which is using that context:

const CorporateSettingsPage: React.FC<CorporateSettingsPageProps> = ({
  apiBaseUrl,
  campusBaseUrl,
  ecomBaseUrl,
}: CorporateSettingsPageProps) => {
  const corporateContext = useContext(CorporateContext);

  console.log('corporate context is:');    //<-- ALWAYS RETURNS DEFAULT VALUES
  console.log(corporateContext);


  useEffect(() => {
    (async () => {
      try {
        const json = await fetchCorporateSettings(apiBaseUrl, 
corporateContext.corporateId);
  ...
    })();
  }, [corporateContext]);

  return (
      <CorporateWrapper apiBaseUrl={apiBaseUrl}> // <--- PARENT COMPONENT WITH CONTEXT INSIDE
        <div>
           ...
           <SomeOtherComponent />   // <-- CONTEXT IS CORRECT HERE AND UPDATED VALUES ARE SHOWN
        </div>
      </CorporateWrapper>
  );
like image 559
Denis2310 Avatar asked Oct 21 '25 16:10

Denis2310


2 Answers

Try to do these things:

  1. First ensure that the state is correctly updating. This should be enough to debug:
useEffect(()=>{
console.log(corporateContextDefaults);
},[corporateContextDefaults])
  1. If the state is updating correctly the problem is in your Provider->Consumer relation.

Verify that your consumer is a child of the providing component.

like image 63
Andrea Costanzo Avatar answered Oct 23 '25 05:10

Andrea Costanzo


React docs state: "All consumers that are descendants of a Provider will re-render whenever the Provider’s value prop changes.". Your CorporateSettingsPage component won't be able to useContext(CorporateContext) because it's not a descendant of CorporateWrapper whereas SomeOtherComponent which is a descendant will be able to.

like image 39
Ben Stickley Avatar answered Oct 23 '25 05:10

Ben Stickley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!