Search code examples
react-query

React Query Kit how to do a conditional get request with params correctly?


I am currently working on a project that uses react query kit and I don't quite grasp how to use their api correctly.

I have a get request with a param where I want to fetch a cityname based on a postal code, so I created a custom hook that I call in my component:

Custom Hook:

import { createQuery } from "react-query-kit";
import { request } from "@/lib/proxyClient";
import { RequestError } from "@/shared/helpers/RequestError";

export const useAutofillCityName = createQuery({
  primaryKey: "/api/postal-code",
  queryFn: async ({ queryKey: [primaryKey] }) => {
    try {
      const response = await request.get<any>(primaryKey, { params: { postal_code: "12345" } });
      return response?.data;
    } catch (err) {
      throw new RequestError(err);
    }
  },
  useErrorBoundary: false,
});

And the call of that hook

const [triggerQuery, setTriggerQuery] = useState(false);

const { data, error, isLoading } = useAutofillCityName({
    enabled: triggerQuery, // This ensures the query runs only if postalCode is entered
  });

I basically set the trigger to true when I want to fetch the postalCode, is this really the correct way to use this api? It seems super complicated, also how would I pass a postalCode as a param?


Solution

  • Your on the right track with what you have there. If we look at the offical docs for react-query-kit they have a good example of how to pass a variable https://tanstack.com/query/v4/docs/framework/react/community/liaoliao666-react-query-kit

    So with your example, you just need to pass a variable object to the hook and use that within the hook. You also need to make sure its passed along to the queryKey so it gets cached properly

    
    type Response = { } // whatever your response is
    type Variables = { postCode: number }
    
    export const useAutofillCityName = createQuery<Response, Variables, Error>({
      primaryKey: "/api/postal-code",
      queryFn: async ({ queryKey: [primaryKey, variables] }) => {
        try {
          const response = await request.get<any>(primaryKey, { params: { postal_code: variables.postCode } });
          return response?.data;
        } catch (err) {
          throw new RequestError(err);
        }
      },
      useErrorBoundary: false,
    });
    
    
    
    const [triggerQuery, setTriggerQuery] = useState(false);
    
    const { data } = useAutofillCityName({ 
     variables: { postCode: 1234 },
     enabled: triggerQuery
    })