我有一个调用 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。
您是否尝试过将
enabled
设置为 false
?
enabled
设置为 false
以防止自动 API 调用。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();
};
解释