Open History to see the last commit
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 )
30}
31β
32// All you have to do now is pass a key!
33function Posts() {
34 const { status, data, error, isFetching } = useQuery(['/posts'])
35β
36 // ...
37}
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 // ...
46}
47```
48β
49If you ever want to override the default queryFn, you can just provide your own like you normally would.