如果您发现自己因为任何原因希望可以为整个应用共享相同的查询函数,并且只使用查询键来标识应该获取什么,您可以通过为 TanStack Query 提供默认查询函数来实现。
// Define a default query function that will receive the query key
const defaultQueryFn = async ({ queryKey }) => {
const { data } = await axios.get(
`https://jsonplaceholder.typicode.com${queryKey[0]}`,
)
return data
}
// provide the default query function to your app with defaultOptions
const queryClient = new QueryClient({
defaultOptions: {
queries: {
queryFn: defaultQueryFn,
},
},
})
function App() {
return (
<QueryClientProvider client={queryClient}>
<YourApp />
</QueryClientProvider>
)
}
// All you have to do now is pass a key!
function Posts() {
const { status, data, error, isFetching } = useQuery({ queryKey: ['/posts'] })
// ...
}
// You can even leave out the queryFn and just go straight into options
function Post({ postId }) {
const { status, data, error, isFetching } = useQuery({
queryKey: [`/posts/${postId}`],
enabled: !!postId,
})
// ...
}
// Define a default query function that will receive the query key
const defaultQueryFn = async ({ queryKey }) => {
const { data } = await axios.get(
`https://jsonplaceholder.typicode.com${queryKey[0]}`,
)
return data
}
// provide the default query function to your app with defaultOptions
const queryClient = new QueryClient({
defaultOptions: {
queries: {
queryFn: defaultQueryFn,
},
},
})
function App() {
return (
<QueryClientProvider client={queryClient}>
<YourApp />
</QueryClientProvider>
)
}
// All you have to do now is pass a key!
function Posts() {
const { status, data, error, isFetching } = useQuery({ queryKey: ['/posts'] })
// ...
}
// You can even leave out the queryFn and just go straight into options
function Post({ postId }) {
const { status, data, error, isFetching } = useQuery({
queryKey: [`/posts/${postId}`],
enabled: !!postId,
})
// ...
}
如果您想覆盖默认的 queryFn,您可以像往常一样提供您自己的。