Adding useQuery to an existing custom hook in React

195 views Asked by At

I am learning React and following a YouTube course on setting up persistent login by Dave Gray (Course here). In this course there is a custom hook that encapsulates the persistent login functionality by calling returning a function that can be used to fetch an access token whenever the access token is expired. The custom hook is below:

import axios from "../api/axios";
import useAuth from "./useAuth";

const useRefreshToken = () => {
  const { setAuth } = useAuth();
  const refresh = async () => {
    const response = await axios.get("/api/v1/refreshtoken", {
      withCredentials: true,
    });
    setAuth((prev) => {
      console.log(JSON.stringify("prevstate: ", prev));
      console.log("response body", response.data.body);
      return {
        ...prev,
        role: response.data.body.role,
        username: response.data.body.username,
        accessToken: response.data.body.access_token,
      };
    });
    return response.data.body.access_token;
  };
  return refresh;
};

export default useRefreshToken;

I have this working as expected but find that in dev mode, the service call to fetch the refresh token is happening two times. I learned that this is due to React running in strict mode in dev environment, and is meant to expose potential issues in code.

I am trying to implement tanstack useQuery around the axios call in the hook so that the second request fetches the data from cache without going out to the backend, but I am having issues with the implementation. Can any one help explain how I can add useQuery in this hook?

I tried adding useQuery like below:

import { useQuery, useQueryClient } from "@tanstack/react-query";
import axios from "../api/axios";
import useAuth from "./useAuth";

const refresh = async () => {
  return axios.get("/api/v1/refreshtoken", {
    withCredentials: true,
  });
};

const useRefreshToken = () => {
  const { setAuth } = useAuth();
  const queryClient = useQueryClient();
  //TODO: Update this hook to use react-query's useQuery hook so that it handles instances of multiple calls seamlessly.
  return useQuery(["refreshtoken"], refresh, {
    // initialData: () => {queryClient.get},
    onSuccess: (response) => {
      setAuth((prev) => {
        console.log(JSON.stringify("prevstate: ", prev));
        console.log("response body", response.data.body);
        return {
          ...prev,
          role: response.data.body.role,
          username: response.data.body.username,
          accessToken: response.data.body.access_token,
        };
      });
      return response.data.body.accessToken;
    },
  });
};

export default useRefreshToken;

However, I faced issue where I could not use the hook conditionally or within a useEffect

0

There are 0 answers