Skip to content

Commit 9df60c9

Browse files
committed
2 parents 641add1 + 2616dcc commit 9df60c9

File tree

13 files changed

+325
-137
lines changed

13 files changed

+325
-137
lines changed

docs/src/pages/docs/api.md

Lines changed: 70 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,6 @@ const {
2424
} = useQuery(queryKey, queryFn?, {
2525
cacheTime,
2626
enabled,
27-
forceFetchOnMount,
2827
initialData,
2928
initialStale,
3029
isDataEqual,
@@ -142,10 +141,6 @@ const queryInfo = useQuery({
142141
- Optional
143142
- Defaults to `false`
144143
- If set, any previous `data` will be kept when fetching new data because the query key changed.
145-
- `forceFetchOnMount: Boolean`
146-
- Optional
147-
- Defaults to `false`
148-
- Set this to `true` to always fetch when the component mounts (regardless of staleness).
149144
- `queryFnParamsFilter: Function(args) => filteredArgs`
150145
- Optional
151146
- This function will filter the params that get passed to `queryFn`.
@@ -362,9 +357,11 @@ const queryCache = new QueryCache({
362357
363358
Its available properties and methods are:
364359
360+
- [`fetchQuery`](#querycachefetchquery)
365361
- [`prefetchQuery`](#querycacheprefetchquery)
366362
- [`getQueryData`](#querycachegetquerydata)
367363
- [`setQueryData`](#querycachesetquerydata)
364+
- [`refetchQueries`](#querycacherefetchqueries)
368365
- [`invalidateQueries`](#querycacheinvalidatequeries)
369366
- [`cancelQueries`](#querycachecancelqueries)
370367
- [`removeQueries`](#querycacheremovequeries)
@@ -380,9 +377,25 @@ Its available properties and methods are:
380377
- Optional
381378
- Define defaults for all queries and mutations using this query cache.
382379
380+
## `queryCache.fetchQuery`
381+
382+
`fetchQuery` is an asynchronous method that can be used to fetch and cache a query. It will either resolve with the data or throw with the error. Specify a `staleTime` to only trigger a fetch when the data is stale. Use the `prefetchQuery` method if you just want to fetch a query without needing the result.
383+
384+
```js
385+
try {
386+
const data = await queryCache.fetchQuery(queryKey, queryFn)
387+
} catch (error) {
388+
console.log(error)
389+
}
390+
```
391+
392+
**Returns**
393+
394+
- `Promise<TResult>`
395+
383396
## `queryCache.prefetchQuery`
384397
385-
`prefetchQuery` is an asynchronous function that can be used to fetch and cache a query response before it is needed or rendered with `useQuery` and friends.
398+
`prefetchQuery` is an asynchronous method that can be used to fetch and cache a query response before it is needed or rendered with `useQuery` and friends.
386399
387400
- If either:
388401
- The query does not exist or
@@ -394,13 +407,13 @@ Its available properties and methods are:
394407
> The difference between using `prefetchQuery` and `setQueryData` is that `prefetchQuery` is async and will ensure that duplicate requests for this query are not created with `useQuery` instances for the same query are rendered while the data is fetching.
395408
396409
```js
397-
const data = await queryCache.prefetchQuery(queryKey, queryFn)
410+
await queryCache.prefetchQuery(queryKey, queryFn)
398411
```
399412
400413
To pass options like `force` or `throwOnError`, use the fourth options object:
401414
402415
```js
403-
const data = await queryCache.prefetchQuery(queryKey, queryFn, config, {
416+
await queryCache.prefetchQuery(queryKey, queryFn, config, {
404417
force: true,
405418
throwOnError: true,
406419
})
@@ -409,7 +422,7 @@ const data = await queryCache.prefetchQuery(queryKey, queryFn, config, {
409422
You can even use it with a default queryFn in your config!
410423
411424
```js
412-
const data = await queryCache.prefetchQuery(queryKey)
425+
await queryCache.prefetchQuery(queryKey)
413426
```
414427
415428
**Options**
@@ -423,7 +436,7 @@ The options for `prefetchQuery` are exactly the same as those of [`useQuery`](#u
423436
424437
**Returns**
425438
426-
- `promise: Promise`
439+
- `Promise<TResult | undefined>`
427440
- A promise is returned that will either immediately resolve with the query's cached response data, or resolve to the data returned by the fetch function. It **will not** throw an error if the fetch fails. This can be configured by setting the `throwOnError` option to `true`.
428441
429442
## `queryCache.getQueryData`
@@ -478,6 +491,52 @@ For convenience in syntax, you can also pass an updater function which receives
478491
setQueryData(queryKey, oldData => newData)
479492
```
480493
494+
## `queryCache.refetchQueries`
495+
496+
The `refetchQueries` method can be used to refetch queries based on certain conditions.
497+
498+
Examples:
499+
500+
```js
501+
// refetch all queries:
502+
await queryCache.refetchQueries()
503+
504+
// refetch all stale queries:
505+
await queryCache.refetchQueries([], { stale: true })
506+
507+
// refetch all stale and active queries:
508+
await queryCache.refetchQueries([], { stale: true, active: true })
509+
510+
// refetch all queries partially matching a query key:
511+
await queryCache.refetchQueries(['posts'])
512+
513+
// refetch all queries exactly matching a query key:
514+
await queryCache.refetchQueries(['posts', 1], { exact: true })
515+
```
516+
517+
**Options**
518+
519+
- `queryKeyOrPredicateFn` can either be a [Query Key](#query-keys) or a `Function`
520+
- `queryKey: QueryKey`
521+
- If a query key is passed, queries will be filtered to those where this query key is included in the existing query's query key. This means that if you passed a query key of `'todos'`, it would match queries with the `todos`, `['todos']`, and `['todos', 5]`. See [Query Keys](./guides/queries#query-keys) for more information.
522+
- `query => boolean`
523+
- This predicate function will be called for every single query in the cache and be expected to return truthy for queries that are `found`.
524+
- The `exact` option has no effect when using a function
525+
- `exact?: boolean`
526+
- If you don't want to search queries inclusively by query key, you can pass the `exact: true` option to return only the query with the exact query key you have passed. Remember to destructure it out of the array!
527+
- `active?: boolean`
528+
- When set to `true` it will refetch active queries.
529+
- When set to `false` it will refetch inactive queries.
530+
- `stale?: boolean`
531+
- When set to `true` it will match on stale queries.
532+
- When set to `false` it will match on fresh queries.
533+
- `throwOnError?: boolean`
534+
- When set to `true`, this method will throw if any of the query refetch tasks fail.
535+
536+
**Returns**
537+
538+
This function returns a promise that will resolve when all of the queries are done being refetched. By default, it **will not** throw an error if any of those queries refetches fail, but this can be configured by setting the `throwOnError` option to `true`
539+
481540
## `queryCache.invalidateQueries`
482541
483542
The `invalidateQueries` method can be used to invalidate and refetch single or multiple queries in the cache based on their query keys or any other functionally accessible property/state of the query. By default, all matching queries are immediately marked as stale and active queries are refetched in the background.
@@ -549,7 +608,7 @@ This function does not return anything
549608
The `removeQueries` method can be used to remove queries from the cache based on their query keys or any other functionally accessible property/state of the query.
550609

551610
```js
552-
const queries = queryCache.removeQueries(queryKeyOrPredicateFn, {
611+
queryCache.removeQueries(queryKeyOrPredicateFn, {
553612
exact,
554613
})
555614
```

docs/src/pages/docs/comparison.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ Feature/Capability Key:
1212
- 🔶 Supported and documented, but requires extra user-code to implement
1313
- 🛑 Not officially supported or documented.
1414

15-
| | React Query | SWR [_(Website)_](swr) | Apollo Client [_(Website)_](apollo) |
15+
| | React Query | SWR [_(Website)_][swr] | Apollo Client [_(Website)_][apollo] |
1616
| -------------------------------------------- | -------------------------------------- | -------------------------- | ------------------------------------- |
1717
| Supported Query Syntax | Promise, REST, GraphQL | Promise, REST, GraphQL | GraphQL |
1818
| Supported Query Keys | JSON | JSON | GraphQL Query |

docs/src/pages/docs/guides/prefetching.md

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,11 @@ id: prefetching
33
title: Prefetching
44
---
55

6-
If you're lucky enough, you may know enough about what your users will do to be able to prefetch the data they need before it's needed! If this is the case, you can use the `prefetchQuery` function to prefetch the results of a query to be placed into the cache:
6+
If you're lucky enough, you may know enough about what your users will do to be able to prefetch the data they need before it's needed! If this is the case, you can use the `fetchQuery` or `prefetchQuery` methods to prefetch the results of a query to be placed into the cache:
77

88
```js
99
const prefetchTodos = async () => {
10-
const queryData = await queryCache.prefetchQuery('todos', () =>
11-
fetch('/todos')
12-
)
10+
await queryCache.prefetchQuery('todos', () => fetch('/todos'))
1311
// The results of this query will be cached like a normal query
1412
}
1513
```

docs/src/pages/docs/guides/ssr.md

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -118,12 +118,12 @@ Since there are many different possible setups for SSR, it's hard to give a deta
118118
> Note: The global `queryCache` you can import directly from 'react-query' does not cache queries on the server to avoid leaking sensitive information between requests.
119119
120120
- Prefetch data
121-
- Create a `prefetchQueryCache` specifically for prefetching by calling `const prefetchQueryCache = new QueryCache()`
122-
- Call `prefetchQueryCache.prefetchQuery(...)` to prefetch queries
123-
- Dehydrate by using `const dehydratedState = dehydrate(prefetchQueryCache)`
121+
- Create a `prefetchCache` specifically for prefetching by calling `const prefetchCache = new QueryCache()`
122+
- Call `prefetchCache.prefetchQuery(...)` to prefetch queries
123+
- Dehydrate by using `const dehydratedState = dehydrate(prefetchCache)`
124124
- Render
125-
- Create a new render query cache and hydrate the state. Use this query cache to render your app.
126-
- **Do not** use the `prefetchQueryCache` to render your app, the server and client both needs to render from the dehydrated data to avoid React hydration mismatches. This is because queries with errors are excluded from dehydration by default.
125+
- Create a new query cache for rendering and hydrate the state. Use this query cache to render your app.
126+
- **Do not** use the `prefetchCache` to render your app, the server and client both needs to render from the dehydrated data to avoid React hydration mismatches. This is because queries with errors are excluded from dehydration by default.
127127
- Serialize and embed `dehydratedState` in the markup
128128
- Security note: Serializing data with `JSON.stringify` can put you at risk for XSS-vulnerabilities, [this blog post explains why and how to solve it](https://medium.com/node-security/the-most-common-xss-vulnerability-in-react-js-applications-2bdffbcc1fa0)
129129

@@ -180,7 +180,7 @@ ReactDOM.hydrate(
180180

181181
Any query with an error is automatically excluded from dehydration. This means that the default behaviour is to pretend these queries were never loaded on the server, usually showing a loading state instead, and retrying the queries on the client. This happens regardless of error.
182182

183-
Sometimes this behavior is not desirable, maybe you want to render an error page with a correct status code instead on certain errors or queries. In those cases, pass `throwOnError: true` to the specific `prefetchQuery` to be able to catch and handle those errors manually.
183+
Sometimes this behavior is not desirable, maybe you want to render an error page with a correct status code instead on certain errors or queries. In those cases, use `fetchQuery` and catch any errors to handle those manually.
184184

185185
**Staleness is measured from when the query was fetched on the server**
186186

src/core/query.ts

Lines changed: 14 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -110,7 +110,7 @@ export class Query<TResult, TError> {
110110
cacheTime: number
111111

112112
private queryCache: QueryCache
113-
private promise?: Promise<TResult | undefined>
113+
private promise?: Promise<TResult>
114114
private gcTimeout?: number
115115
private cancelFetch?: (silent?: boolean) => void
116116
private continueFetch?: () => void
@@ -160,12 +160,15 @@ export class Query<TResult, TError> {
160160
}, this.cacheTime)
161161
}
162162

163-
async cancel(silent?: boolean): Promise<void> {
163+
cancel(silent?: boolean): Promise<undefined> {
164164
const promise = this.promise
165+
165166
if (promise && this.cancelFetch) {
166167
this.cancelFetch(silent)
167-
await promise.catch(noop)
168+
return promise.then(noop).catch(noop)
168169
}
170+
171+
return Promise.resolve(undefined)
169172
}
170173

171174
private continue(): void {
@@ -316,17 +319,17 @@ export class Query<TResult, TError> {
316319
}
317320
}
318321

319-
async refetch(
322+
refetch(
320323
options?: RefetchOptions,
321324
config?: ResolvedQueryConfig<TResult, TError>
322325
): Promise<TResult | undefined> {
323-
try {
324-
return await this.fetch(undefined, config)
325-
} catch (error) {
326-
if (options?.throwOnError === true) {
327-
throw error
328-
}
326+
let promise: Promise<TResult | undefined> = this.fetch(undefined, config)
327+
328+
if (!options?.throwOnError) {
329+
promise = promise.catch(noop)
329330
}
331+
332+
return promise
330333
}
331334

332335
fetchMore(
@@ -348,7 +351,7 @@ export class Query<TResult, TError> {
348351
async fetch(
349352
options?: FetchOptions,
350353
config?: ResolvedQueryConfig<TResult, TError>
351-
): Promise<TResult | undefined> {
354+
): Promise<TResult> {
352355
if (this.promise) {
353356
if (options?.fetchMore && this.state.data) {
354357
// Silently cancel current fetch if the user wants to fetch more

0 commit comments

Comments
 (0)