0

I am trying to pass the params to the react query through the hook.

export const useUserInfo = (enabled, {token}) => {
  return useQuery(
    ["users-info", token],
    () => fetchUserInfo(token),
    {
      enabled: enabled,
    },
  );
};

const Auth = () => {
    const { refetch } = useUserInfo(false);  // calling this hook and getting refetch
    
      const handleLoginPopup = async () => {
       try {
           const token = "abcd121212"

         const { data: userInfo } = await refetch(true, {token:token }); // Here I want to pass a token 

         dispatch({ type: "SET_USER", payload: userInfo });

         navigate("/");
         location.reload();
    } catch (error) {
      console.error(error);
    }
  };
}

Here, But I am not able to pass it. as I am getting an error as token is undefined here even after defining it . also I tried giving a default value as well.

Can any one help me in passing the extra params to the react query hook.

ganesh kaspate
  • 1
  • 9
  • 41
  • 88

1 Answers1

0

As explained in the link presented by @Rayon, I think you have the wrong approach altogether.

The token is a state and the query should be disabled until the token state is updated with the token. After the userInfo has been fetched we call dispatch and navigate in a useEffect.

export const useUserInfo = (token) => {
  return useQuery(
    ["users-info", token],
    () => fetchUserInfo(token),
    {
      enabled: !!token, // disable when we don't have a token
    },
  );
};

const Auth = () => {
  const [token, setToken] = useState();

  const { data: userInfo } = useUserInfo(false);
    
  const handleLoginPopup = async () => {
      const token = setToken("abcd121212")
  };

  useEffect(() => {
    if (userInfo) {
      dispatch({ type: "SET_USER", payload: userInfo });
      navigate("/");
    }
  }, [userInfo]);
}
Anton
  • 1,045
  • 1
  • 7
  • 16