Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

default-query-function.md

49 lines1.3 KB

1---
2id: default-query-function
3title: Default Query Function
4---
5​
6If you find yourself wishing for whatever reason that you could just share the same query function for your entire app and just use query keys to identify what it should fetch, you can do that by providing a **default query function** to React Query:
7​
8```js
9// Define a default query function that will receive the query key
10const defaultQueryFn = async ({ queryKey }) => {
11 const { data } = await axios.get(`https://jsonplaceholder.typicode.com${queryKey[0]}`);
12 return data;
13};
14​
15// provide the default query function to your app with defaultOptions
16const queryClient = new QueryClient({
17 defaultOptions: {
18 queries: {
19 queryFn: defaultQueryFn,
20 },
21 },
22})
23​
24function App() {
25 return (
26 <QueryClientProvider client={queryClient}>
27 <YourApp />
28 </QueryClientProvider>
29 )
31​
32// All you have to do now is pass a key!
33function Posts() {
34 const { status, data, error, isFetching } = useQuery(['/posts'])
35​
36 // ...
38​
39// You can even leave out the queryFn and just go straight into options
40function Post({ postId }) {
41 const { status, data, error, isFetching } = useQuery([`/posts/${postId}`], {
42 enabled: !!postId,
43 })
44​
45 // ...
47```
48​
49If you ever want to override the default queryFn, you can just provide your own like you normally would.