2
  1. I have created one wrapper component where I put my react context.

  2. Inside that wrapper component I have used useEffect() hook where I fetch values from api and try to update context default values.

  3. In my child component I tried to fetch context values but only default value of that context is fetched. So it seems that useEffect hook didnt updated my context object.

Here is wrapper component:

export const CorporateWrapper = ({ apiBaseUrl, children }) => {
const [corporateContextDefaults, setCorporateContextDefaults] = useState({});

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

                if (json.success !== true) {
                    console.log(json.message);

                    return {
                        notFound: true,
                    };
                }

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

return (
    <CorporateProvider value={corporateContextDefaults}>
        {children}
    </CorporateProvider>
);

};

Here is CorporateProvider component:

import React, { useState, useContext } from "react";

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

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

export const useUpdateCorporateContext = () => {
    return useContext(UpdateCorporateContext);
};

export const CorporateProvider = ({ value, children }) => {
    const [details, setDetails] = useState(value);
    return (
        <CorporateContext.Provider value={details}>
            <UpdateCorporateContext.Provider value={setDetails}>
            {children}
            </UpdateCorporateContext.Provider>
        </CorporateContext.Provider>
    );
};

export default CorporateProvider;

Here is how I try to fetch context value from child component which is wrapped under wrapper component:

const { corporateId } = useCorporateContext();
1
  • It looks like you asked the same question again. Please update your question instead of asking the same one again. Commented Jan 23, 2022 at 3:11

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.