skip to Main Content

I’m trying to route the user on login to a page depending on data I get from a useQuery call , but the onSuccess is too quick to run while the query hasn’t fetch yet , my code looks like this

  const { data, refetch } = useQuery(["tracks"], getTracks, {
    enabled: false,
  });

  const { mutate, isLoading, isError, error } = useMutation(login, {
    onSuccess(d, v, c) {
      Cookies.set("cookieToken", d?.access);

      let type = Cookies.get("cookieToken");
      type = parseJwt(type);
      type = type.user_type;
      refetch();

      if (data) {
        if (type === 5 || type === 6) {
          navigate(`/${data?.object[0]?.id}?type=prio`);
        } else {
          navigate(`/${data?.object[0]?.id}?type=filtering`);
        }
      }
    },
  });

I want to onSuccess of the use mutation to fetch the query , wait for the result and navigate the user based on the data I get from the query , how to do so ?

I can’t run the useQuery before the onSuccess because it won’t succeed without having the token from the mutation

2

Answers


  1. I think you need to await the refetch, so something like this:

     const { mutate, isLoading, isError, error } = useMutation(login, {
        onSuccess: async (d, v, c) => {
          Cookies.set("cookieToken", d?.access);
    
          let type = Cookies.get("cookieToken");
          type = parseJwt(type);
          type = type.user_type;
          await refetch();
    
          if (data) {
            if (type === 5 || type === 6) {
              navigate(`/${data?.object[0]?.id}?type=prio`);
            } else {
              navigate(`/${data?.object[0]?.id}?type=filtering`);
            }
          }
        },
      });
    
    Login or Signup to reply.
  2. Assuming you are using @tanstack/react-query v4+, maybe something like this might help?

     const { data, refetch } = useQuery(["tracks"], getTracks, {
        enabled: false,
     });
    
     const { mutate, isLoading, isError, error } = useMutation(login, {
        onSuccess: async (d, v, c) => {
          Cookies.set("cookieToken", d?.access);
    
          let type = Cookies.get("cookieToken");
          type = parseJwt(type);
          type = type.user_type;
    
          // Await until refetch completes and use the data 
          // straight from response instead of "data" from the 
          // "useQuery" hook
          const response = await refetch();
    
          if (response.data) {
            if (type === 5 || type === 6) {
              navigate(`/${response.data?.object[0]?.id}?type=prio`);
            } else {
              navigate(`/${response.data?.object[0]?.id}?type=filtering`);
            }
          }
        },
      });
    

    Please refer to the "refetch" function signature and note that it returns a promise:
    https://tanstack.com/query/v4/docs/react/reference/useQuery

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search