'React-Query Prefetch query doesnt return value?

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?



Solution 1:[1]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 TkDodo