Reputation: 3
I have a service that calls an API, and when I first load the page, I want it not to be called. However, the API call function runs multiple times when I load the page for the first time. Please help me check this. I am using Vue Query from TanStack. Thank you very much!
This is my usePostFetch function:
export const usePostFetch = (url, body, configs, queryOptions) => {
const context = useQuery({
queryKey: [url, body, configs?.params],
queryFn: ({ queryKey, meta }) => fetcherByPost({ queryKey, meta }, configs),
enabled: !!url,
...getDefaultOptions(queryOptions)
})
return context
}
This is my service:
getAllCities: (country, state, configs) => {
const body = { country: country, state: state }
return usePostFetch(`${COUNTRY_BASE}/countries/state/cities`, body, {
configs
})
}
Here is where I call the service to use:
const {
data: citiesData,
isLoading: citiesLoading,
isError: iErrorCities,
isSuccess: citiesIsSuccess
} = countriesService.getAllCities(selectedCountry, selectedState, {enabled: false})
api has been called automatically many times: image here
I want the api not to be called automatically when I first enter the page.
Upvotes: 0
Views: 52
Reputation: 974
have you tried to set enabled
to false
?
enabled
to false
to prevent automatic API calls.refetch
function to trigger the API call when needed manually.export const usePostFetch = (url, body, configs, queryOptions) => {
const context = useQuery({
queryKey: [url, body, configs?.params],
queryFn: ({ queryKey, meta }) => fetcherByPost({ queryKey, meta }, configs),
enabled: !!url && queryOptions?.enabled !== false,
...getDefaultOptions(queryOptions)
});
return context;
}
const {
data: citiesData,
isLoading: citiesLoading,
isError: iErrorCities,
isSuccess: citiesIsSuccess,
refetch // This function can be used to manually trigger the API call
} = countriesService.getAllCities(selectedCountry, selectedState, { enabled: false });
// Call refetch when you want to fetch the data, for example on a button click or after a specific event
const fetchCities = () => {
refetch();
};
Explanation
Upvotes: 0