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
10// the queryKey is guaranteed to be an Array here
11const defaultQueryFn = async ({ queryKey }) => {
12 const { data } = await axios.get(`https://jsonplaceholder.typicode.com${queryKey[0]}`);
13 return data;
14};
15β
16// provide the default query function to your app with defaultOptions
17const queryClient = new QueryClient({
18 defaultOptions: {
19 queries: {
20 queryFn: defaultQueryFn,
21 },
22 },
23})
24β
25function App() {
26 return (
27 <QueryClientProvider client={queryClient}>
28 <YourApp />
29 </QueryClientProvider>
30 )
31}
32β
33// All you have to do now is pass a key!
34function Posts() {
35 const { status, data, error, isFetching } = useQuery('/posts')
36β
37 // ...
38}
39β
40// You can even leave out the queryFn and just go straight into options
41function Post({ postId }) {
42 const { status, data, error, isFetching } = useQuery(`/posts/${postId}`, {
43 enabled: !!postId,
44 })
45β
46 // ...
47}
48```
49β
50If you ever want to override the default queryFn, you can just provide your own like you normally would.