Skip to content

Commit 2a31f8d

Browse files
committed
feat: add default quernFn option
This feature allows you to set a default query function in the config and use it for your whole app, similar to how early SWR user's were just passing a url. Now you can do the same and just do `useQuery('/todos')` :)
1 parent 0bf38da commit 2a31f8d

22 files changed

+10759
-71
lines changed

README.md

Lines changed: 55 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -231,6 +231,7 @@ This library is being built and maintained by me, @tannerlinsley and I am always
231231
- [Suspense Mode](#suspense-mode)
232232
- [Fetch-on-render vs Fetch-as-you-render](#fetch-on-render-vs-fetch-as-you-render)
233233
- [Canceling Query Requests](#canceling-query-requests)
234+
- [Using a Defualt Query Function](#using-a-default-query-function)
234235
- [Mutations](#mutations)
235236
- [Basic Mutations](#basic-mutations)
236237
- [Mutation Variables](#mutation-variables)
@@ -1123,6 +1124,51 @@ const query = useQuery('todos', () => {
11231124
})
11241125
```
11251126
1127+
## Using a Defualt Query Function
1128+
1129+
If 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 to identify what it should fetch, you can do that by providing a **default query function** to React Query:
1130+
1131+
```js
1132+
// Define a default query function that will recieve the query key
1133+
const defaultQueryFn = async key => {
1134+
const { data } = await axios.get(`https://jsonplaceholder.typicode.com${key}`)
1135+
return data
1136+
}
1137+
1138+
function App() {
1139+
// provide the default query function to your app via the config provider
1140+
return (
1141+
<ReactQueryConfigProvider
1142+
config={{
1143+
queries: {
1144+
queryFn: defaultQueryFn,
1145+
},
1146+
}}
1147+
>
1148+
<YourApp />
1149+
</ReactQueryConfigProvider>
1150+
)
1151+
}
1152+
1153+
// All you have to do now is pass a key!
1154+
function Posts() {
1155+
const { status, data, error, isFetching } = useQuery('/posts')
1156+
1157+
// ...
1158+
}
1159+
1160+
// You can even leave out the queryFn and just go straight into options
1161+
function Post({ postId }) {
1162+
const { status, data, error, isFetching } = useQuery(`/posts/${postId}`, {
1163+
enabled: postId,
1164+
})
1165+
1166+
// ...
1167+
}
1168+
```
1169+
1170+
If you ever want to override the default queryFn, you can just provide your own like you normally would.
1171+
11261172
# Mutations
11271173
11281174
Unlike queries, mutations are typically used to create/update/delete data or perform server side-effects. For this purpose, React Query exports a `useMutation` hook.
@@ -1661,7 +1707,7 @@ const {
16611707
isFetching,
16621708
failureCount,
16631709
refetch,
1664-
} = useQuery(queryKey, queryFn, {
1710+
} = useQuery(queryKey, queryFn?, {
16651711
suspense,
16661712
queryKeySerializerFn,
16671713
enabled,
@@ -1698,7 +1744,7 @@ const queryInfo = useQuery({
16981744
- If a `[String, ...any]` array is passed, each item will be serialized into a stable query key. See [Query Keys](#query-keys) for more information.
16991745
- The query will automatically update when this key changes (as long as `enabled` is not set to `false`).
17001746
- `queryFn: Function(variables) => Promise(data/error)`
1701-
- **Required**
1747+
- **Required, but only if no default query function has been defined**
17021748
- The function that the query will use to request data.
17031749
- Receives the following variables in the order that they are provided:
17041750
- Query Key Variables
@@ -1968,12 +2014,6 @@ The `queryCache` instance is the backbone of React Query that manages all of the
19682014
const data = await queryCache.prefetchQuery(queryKey, queryFn)
19692015
```
19702016
1971-
For convenience in syntax, you can also pass optional query variables to `prefetchQuery` just like you can `useQuery`:
1972-
1973-
```js
1974-
const data = await queryCache.prefetchQuery(queryKey, queryFn, config)
1975-
```
1976-
19772017
To pass options like `force` or `throwOnError`, use the fourth options object:
19782018
19792019
```js
@@ -1983,6 +2023,12 @@ const data = await queryCache.prefetchQuery(queryKey, queryFn, config, {
19832023
})
19842024
```
19852025
2026+
You can even use it with a default queryFn in your config!
2027+
2028+
```js
2029+
const data = await queryCache.prefetchQuery(queryKey)
2030+
```
2031+
19862032
### Options
19872033
19882034
The options for `prefetchQuery` are exactly the same as those of [`useQuery`](#usequery) with the exception of the last options object:
@@ -2279,6 +2325,7 @@ const queryConfig = {
22792325
},
22802326
queries: {
22812327
...shared,
2328+
queryFn,
22822329
enabled: true,
22832330
retry: 3,
22842331
retryDelay: attemptIndex => Math.min(1000 * 2 ** attemptIndex, 30000),
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
{
2+
"presets": ["react-app"],
3+
"plugins": ["styled-components"]
4+
}
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
{
2+
"extends": ["react-app", "prettier"],
3+
"rules": {
4+
// "eqeqeq": 0,
5+
// "jsx-a11y/anchor-is-valid": 0
6+
}
7+
}
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
2+
3+
# dependencies
4+
/node_modules
5+
/.pnp
6+
.pnp.js
7+
8+
# testing
9+
/coverage
10+
11+
# production
12+
/build
13+
14+
# misc
15+
.DS_Store
16+
.env.local
17+
.env.development.local
18+
.env.test.local
19+
.env.production.local
20+
21+
npm-debug.log*
22+
yarn-debug.log*
23+
yarn-error.log*
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
{}
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
const path = require('path')
2+
const resolveFrom = require('resolve-from')
3+
4+
const fixLinkedDependencies = config => {
5+
config.resolve = {
6+
...config.resolve,
7+
alias: {
8+
...config.resolve.alias,
9+
react$: resolveFrom(path.resolve('node_modules'), 'react'),
10+
'react-dom$': resolveFrom(path.resolve('node_modules'), 'react-dom'),
11+
},
12+
}
13+
return config
14+
}
15+
16+
const includeSrcDirectory = config => {
17+
config.resolve = {
18+
...config.resolve,
19+
modules: [path.resolve('src'), ...config.resolve.modules],
20+
}
21+
return config
22+
}
23+
24+
module.exports = [
25+
['use-babel-config', '.babelrc'],
26+
['use-eslint-config', '.eslintrc'],
27+
fixLinkedDependencies,
28+
// includeSrcDirectory,
29+
]
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
# Example
2+
3+
To run this example:
4+
5+
- `npm install` or `yarn`
6+
- `npm run start` or `yarn start`
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
{
2+
"private": true,
3+
"scripts": {
4+
"start": "rescripts start",
5+
"build": "rescripts build",
6+
"test": "rescripts test",
7+
"eject": "rescripts eject"
8+
},
9+
"dependencies": {
10+
"axios": "0.19.2",
11+
"react": "^16.8.6",
12+
"react-dom": "^16.8.6",
13+
"react-query": "1.0.12",
14+
"react-query-devtools": "1.0.2",
15+
"react-scripts": "3.0.1",
16+
"stop-runaway-react-effects": "^1.2.0",
17+
"styled-components": "^4.3.2"
18+
},
19+
"devDependencies": {
20+
"@rescripts/cli": "^0.0.11",
21+
"@rescripts/rescript-use-babel-config": "^0.0.8",
22+
"@rescripts/rescript-use-eslint-config": "^0.0.9",
23+
"babel-eslint": "10.0.1"
24+
},
25+
"browserslist": {
26+
"production": [
27+
">0.2%",
28+
"not dead",
29+
"not op_mini all"
30+
],
31+
"development": [
32+
"last 1 chrome version",
33+
"last 1 firefox version",
34+
"last 1 safari version"
35+
]
36+
}
37+
}
Binary file not shown.
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
<!DOCTYPE html>
2+
<html lang="en">
3+
<head>
4+
<meta charset="utf-8" />
5+
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" />
6+
<meta name="viewport" content="width=device-width, initial-scale=1" />
7+
<meta name="theme-color" content="#000000" />
8+
<!--
9+
manifest.json provides metadata used when your web app is installed on a
10+
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
11+
-->
12+
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
13+
<!--
14+
Notice the use of %PUBLIC_URL% in the tags above.
15+
It will be replaced with the URL of the `public` folder during the build.
16+
Only files inside the `public` folder can be referenced from the HTML.
17+
18+
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
19+
work correctly both with client-side routing and a non-root public URL.
20+
Learn how to configure a non-root public URL by running `npm run build`.
21+
-->
22+
<title>React App</title>
23+
</head>
24+
<body>
25+
<noscript>You need to enable JavaScript to run this app.</noscript>
26+
<div id="root"></div>
27+
<!--
28+
This HTML file is a template.
29+
If you open it directly in the browser, you will see an empty page.
30+
31+
You can add webfonts, meta tags, or analytics to this file.
32+
The build step will place the bundled scripts into the <body> tag.
33+
34+
To begin the development, run `npm start` or `yarn start`.
35+
To create a production bundle, use `npm run build` or `yarn build`.
36+
-->
37+
</body>
38+
</html>
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
{
2+
"short_name": "React App",
3+
"name": "Create React App Sample",
4+
"icons": [
5+
{
6+
"src": "favicon.ico",
7+
"sizes": "64x64 32x32 24x24 16x16",
8+
"type": "image/x-icon"
9+
}
10+
],
11+
"start_url": ".",
12+
"display": "standalone",
13+
"theme_color": "#000000",
14+
"background_color": "#ffffff"
15+
}

0 commit comments

Comments
 (0)