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?