- 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>
);
corporateContextDefaultsevery time it changes. In this way we exclude that the problem is not in the state but in the context. If it doesn't log anything or it logs the default value in the last update the problem is in the state