Although the expected value is being retrieved by the retrieveStoreId method (as checked through logging the result of the function call), updating storeId state through context method addStoreId is failing (i.e., returning null all the time). Following is my context file and the state updating code using useEffect:
//Context file:
import { createContext, useState } from "react";
const StoreStatusContext = createContext({
storeId: null,
addStoreId: (storeId) => {},
removeStoreId: () => {},
});
export function StoreStatusContextProvider({ children }) {
const [storeId, setStoreId] = useState(null);
const storeStatusContext = {
storeId: storeId,
addStoreId: (storeId) => setStoreId(storeId),
removeStoreId: () => setStoreId(null),
};
return (
<StoreStatusContext.Provider value={storeStatusContext}>
{children}
</StoreStatusContext.Provider>
);
}
export default StoreStatusContext;
//State update using addStoreId:
const { storeId, addStoreId } = useContext(StoreStatusContext);
useEffect(() => {
async function checkStoreStatus() {
const isStoreIdAvailable = await retrieveStoreId();
// console.log(isStoreIdAvailable);
addStoreId(isStoreIdAvailable);
}
checkStoreStatus();
}, []);
tl;dr: the value of isStoreIdAvailable needs to be passed to addStoreId in order to update storeId state.