seventeen
seventeen

Reputation: 3

Disable automatic API calls after navigating to a page in TanStack Vue

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

Answers (1)

Vinicius Cainelli
Vinicius Cainelli

Reputation: 974

have you tried to set enabled to false?

  1. Set enabled to false to prevent automatic API calls.
  2. Use the 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

Related Questions