skip to Main Content

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,
  };
}

2

Answers


  1. Chosen as BEST ANSWER

    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,
      };
    }
    

  2. you can use useEffect() hook to trigger the re-renders when the context change happens,

    const [contextState, setContextState] = useState(context);
    
      useEffect(() => {
        setContextState(context);
      }, [context]);
    
      const getRequestContext = useCallback(async () => {
        const requestContext = {
          headers: contextState.headers,
          env: contextState.env,
          id: contextState.id ?? ""    
        };
        return requestContext;
      }, [contextState]);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search