-2

I have created a custom hook and a component:

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

const Auth = () => {
  const { instance } = useMsal();

  const handleLoginPopup = async () => {
    try {
      const loginInfo = await instance.loginPopup(
        loginRequest,
      );

      const responseData = useUserInfo()
      console.log(responseData);

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

Here, I am trying to call the useUserInfo hook once the loginPopup request is success. But somehow, I am not able to do this as I am getting an error regarding the hooks which can not be called inside conditions. Can any one help me with this?

Drew Reese
  • 165,259
  • 14
  • 153
  • 181
ganesh kaspate
  • 1
  • 9
  • 41
  • 88
  • You cannot put a hook call inside a function. They have to be top-level within the component definition. The following: `const responseData = useUserInfo()` is invalid usage of a hook. – Mr. Polywhirl Aug 21 '23 at 16:04

1 Answers1

0

As the warning/error states you cannot call hooks inside plain functions. However you could move the hook call to the upper level (to the component's body) and use the refetch function to call the query in the handleLoginPopup function.

export const useUserInfo = () => {
  const query = useQuery({
    queryKey: ["users-info"],
    queryFn: () => fetchUserInfo(),
    enabled: false, // <-- disable fetch on mount
  });
  return query;
};

const Auth = () => {
  const { instance } = useMsal();
  const { refetch, data } = useUserInfo();

   const handleLoginPopup = async () => {
    try {
      const loginInfo = await instance.loginPopup(
        loginRequest,
      );

      await refetch(); // call the query
                       // you can await it so the data below will be up to date
      console.log(data);

      navigate("/home");
    } catch (error) {
      console.error(error);
    }
  };
}
kind user
  • 40,029
  • 7
  • 67
  • 77
  • But the thing is I have to call this hook only if the the first API is success. – ganesh kaspate Aug 21 '23 at 16:07
  • @ganeshkaspate Just found in the docs that you can apparently disable calling the query on mount. So it will be called only on `refetch`. Check it out. – kind user Aug 21 '23 at 16:11