1
const getQueryService = () => {


return {
    login: async (id): Promise<AuthLoginGoogleResponse> => {
      try {
        const result = await authApi.loginGooglePost({
          idToken: {
            id_token: id,
          },
        });
        return result;
      } catch (error) {
        console.error("Google Login Fail", error);
      }
    },
  };
};

// Mutation is only for updating and creating and deleting
const getMutationService = () => {
  return {};
};

const useGoogleLogin = () => {
  const queryClient = useQueryClient();
  const queryService = getQueryService();
  // const { data, isLoading } = useQuery('auth', queryService.login)
  const mutationService = getMutationService();

  const fetchLoginData = async (
    tokenId
  ): Promise<AuthLoginGoogleResponse | void> => {
    return await queryClient.prefetchQuery("auth", async() => {
      return await queryService.login(tokenId);
    });
  };

  return fetchLoginData;
};

I am sending token.Id to API using Post request and I am calling it from component however when I run debugger, preFetchquery is not returning the value retuned from result in getqueryservice function.

Is there a reason why preFetchQuery is not returning the return value from getQueryService.login?

1
  • According to API reference, prefetchQuery doesn't return the data: react-query.tanstack.com/reference/… "Returns Promise<void>: A promise is returned that will either immediately resolve if no fetch is needed or after the query has been executed. It will not return any data or throw any errors." Commented May 6, 2022 at 22:30

1 Answer 1

4

because that's what prefetching does. According to the docs (emphasis mine):

prefetchQuery is an asynchronous method that can be used to prefetch a query before it is needed or rendered with useQuery and friends. The method works the same as fetchQuery except that it will not throw or return any data.

So prefetchQuery just puts data in the cache so that it can be picked up later by useQuery, hence the name: pre-fetch.

If you wan to get data returned, you can use queryClient.fetchQuery instead - but you'd also need to handle errors in case the fetch fails.


To be honest, I'm not sure why you are trying to achieve though. Judging from the code, it looks like you're trying to execute a query when the user wants to login. Please keep in mind that this is not what queries are for. Logging someone in is a prime example for a mutation.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.