When I call getRequestContext anywhere in my app after I have updated context, my callback does not use the new value, but instead always uses the old value. Any ideas on how to ensure that I always retrieve the most up to date context value when getRequestContext is called?
export function useData() {
const context = useContext(dataStateContext);
if (context === undefined) {
throw new Error("useData must be used within a dataProvider");
}
const getRequestContext = useCallback(async () => {
const requestContext = {
headers: context.headers,
env: context.env,
id: context.id ?? ""
};
return requestContext;
}, [context]);
return {
getRequestContext,
};
}
I solved it by using a ref, below is the updated code.
export function useData() {
const context = useContext(dataStateContext);
const contextValueRef = useRef(context);
useEffect(() => {
contextValueRef.current = context;
}, [context]);
if (context === undefined) {
throw new Error("useData must be used within a dataProvider");
}
const getRequestContext = useCallback(async () => {
const updatedContext = contextValueRef.current || context;
const requestContext = {
headers: updatedContext.headers,
env: updatedContext.env,
id: updatedContext.id ?? ""
};
return requestContext;
}, [context]);
return {
getRequestContext,
};
}