导航到 TanStack Vue 中的页面后禁用自动 API 调用

问题描述 投票:0回答:1

我有一个调用 API 的服务,当我第一次加载页面时,我希望它不被调用。但是,当我第一次加载页面时,API调用函数会运行多次。请帮我检查一下。我正在使用 TanStack 的 Vue 查询。非常感谢!

这是我的 usePostFetch 函数:

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
}

这是我的服务:

getAllCities: (country, state, configs) => {
    const body = { country: country, state: state }

    return usePostFetch(`${COUNTRY_BASE}/countries/state/cities`, body, {
      configs
    })
  }

这是我调用要使用的服务的地方:

const {
  data: citiesData,
  isLoading: citiesLoading,
  isError: iErrorCities,
  isSuccess: citiesIsSuccess
} = countriesService.getAllCities(selectedCountry, selectedState, {enabled: false})

api已被自动调用多次: 图片在这里

我希望第一次进入页面时不要自动调用api。

vue.js react-query tanstackreact-query tanstack
1个回答
0
投票

您是否尝试过将

enabled
设置为
false

  1. enabled
    设置为
    false
    以防止自动 API 调用。
  2. 需要时使用
    refetch
    函数手动触发API调用。
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();
};

解释

© www.soinside.com 2019 - 2024. All rights reserved.