Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
111 changes: 40 additions & 71 deletions docs/src/pages/docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -344,36 +344,41 @@ const promise = mutate(variables, {
- `reset: Function() => void`
- A function to clean the mutation internal state (i.e., it resets the mutation to its initial state).

## `queryCache`

The `queryCache` instance is the backbone of React Query that manages all of the state, caching, lifecycle and magic of every query. It supports relatively unrestricted, but safe, access to manipulate query's as you need. Its available properties and methods are:

- [`useQuery`](#usequery)
- [`usePaginatedQuery`](#usepaginatedquery)
- [`useInfiniteQuery`](#useinfinitequery)
- [`useMutation`](#usemutation)
- [`queryCache`](#querycache)
- [`queryCache.prefetchQuery`](#querycacheprefetchquery)
- [`queryCache.getQueryData`](#querycachegetquerydata)
- [`queryCache.setQueryData`](#querycachesetquerydata)
- [`queryCache.invalidateQueries`](#querycacheinvalidatequeries)
- [`queryCache.cancelQueries`](#querycachecancelqueries)
- [`queryCache.removeQueries`](#querycacheremovequeries)
- [`queryCache.getQuery`](#querycachegetquery)
- [`queryCache.getQueries`](#querycachegetqueries)
- [`queryCache.isFetching`](#querycacheisfetching)
- [`queryCache.subscribe`](#querycachesubscribe)
- [`queryCache.clear`](#querycacheclear)
- [`makeQueryCache`](#makequerycache)
- [`useQueryCache`](#usequerycache)
- [`useIsFetching`](#useisfetching)
- [`ReactQueryConfigProvider`](#reactqueryconfigprovider)
- [`ReactQueryCacheProvider`](#reactquerycacheprovider)
- [`setConsole`](#setconsole)
- [`hydration/dehydrate`](#hydrationdehydrate)
- [`hydration/hydrate`](#hydrationhydrate)
- [`hydration/useHydrate`](#hydrationusehydrate)
- [`hydration/ReactQueryCacheProvider`](#hydrationreactquerycacheprovider)
## `QueryCache`

The `QueryCache` is the backbone of React Query that manages all of the state, caching, lifecycle and magic of every query. It supports relatively unrestricted, but safe, access to manipulate query's as you need.

```js
import { QueryCache } from 'react-query'

const queryCache = new QueryCache({
defaultConfig: {
queries: {
staleTime: Infinity,
},
},
})
```

Its available properties and methods are:

- [`prefetchQuery`](#querycacheprefetchquery)
- [`getQueryData`](#querycachegetquerydata)
- [`setQueryData`](#querycachesetquerydata)
- [`invalidateQueries`](#querycacheinvalidatequeries)
- [`cancelQueries`](#querycachecancelqueries)
- [`removeQueries`](#querycacheremovequeries)
- [`getQuery`](#querycachegetquery)
- [`getQueries`](#querycachegetqueries)
- [`isFetching`](#querycacheisfetching)
- [`subscribe`](#querycachesubscribe)
- [`clear`](#querycacheclear)

**Options**

- `defaultConfig: QueryQueryConfig`
- Optional
- Define defaults for all queries and mutations using this query cache.

## `queryCache.prefetchQuery`

Expand Down Expand Up @@ -426,8 +431,6 @@ The options for `prefetchQuery` are exactly the same as those of [`useQuery`](#u
`getQueryData` is a synchronous function that can be used to get an existing query's cached data. If the query does not exist, `undefined` will be returned.

```js
import { queryCache } from 'react-query'

const data = queryCache.getQueryData(queryKey)
```

Expand All @@ -448,8 +451,6 @@ const data = queryCache.getQueryData(queryKey)
> The difference between using `setQueryData` and `prefetchQuery` is that `setQueryData` is sync and assumes that you already synchronously have the data available. If you need to fetch the data asynchronously, it's suggested that you either refetch the query key or use `prefetchQuery` to handle the asynchronous fetch.

```js
import { queryCache } from 'react-query'

queryCache.setQueryData(queryKey, updater, config)
```

Expand Down Expand Up @@ -485,8 +486,6 @@ The `invalidateQueries` method can be used to invalidate and refetch single or m
- If you **want inactive queries to refetch** as well, use the `refetchInactive: true` option

```js
import { queryCache } from 'react-query'

const queries = queryCache.invalidateQueries(inclusiveQueryKeyOrPredicateFn, {
exact,
throwOnError,
Expand Down Expand Up @@ -525,8 +524,6 @@ The `cancelQueries` method can be used to cancel outgoing queries based on their
This is most useful when performing optimistic updates since you will likely need to cancel any outgoing query refetches so they don't clobber your optimistic update when they resolve.

```js
import { queryCache } from 'react-query'

const queries = queryCache.cancelQueries(queryKeyOrPredicateFn, {
exact,
})
Expand All @@ -552,8 +549,6 @@ This function does not return anything
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.

```js
import { queryCache } from 'react-query'

const queries = queryCache.removeQueries(queryKeyOrPredicateFn, {
exact,
})
Expand Down Expand Up @@ -581,8 +576,6 @@ This function does not return anything
> Note: This is not typically needed for most applications, but can come in handy when needing more information about a query in rare scenarios (eg. Looking at the query.state.updatedAt timestamp to decide whether a query is fresh enough to be used as an initial value)

```js
import { queryCache } from 'react-query'

const query = queryCache.getQuery(queryKey)
```

Expand All @@ -603,8 +596,6 @@ const query = queryCache.getQuery(queryKey)
> Note: This is not typically needed for most applications, but can come in handy when needing more information about a query in rare scenarios

```js
import { queryCache } from 'react-query'

const queries = queryCache.getQueries(queryKey)
```

Expand All @@ -623,8 +614,6 @@ const queries = queryCache.getQueries(queryKey)
This `isFetching` property is an `integer` representing how many queries, if any, in the cache are currently fetching (including background-fetching, loading new pages, or loading more infinite query results)

```js
import { queryCache } from 'react-query'

if (queryCache.isFetching) {
console.log('At least one query is fetching!')
}
Expand All @@ -637,8 +626,6 @@ React Query also exports a handy [`useIsFetching`](#useisfetching) hook that wil
The `subscribe` method can be used to subscribe to the query cache as a whole and be informed of safe/known updates to the cache like query states changing or queries being updated, added or removed

```js
import { queryCache } from 'react-query'

const callback = (cache, query) => {}

const unsubscribe = queryCache.subscribe(callback)
Expand All @@ -660,8 +647,6 @@ const unsubscribe = queryCache.subscribe(callback)
The `clear` method can be used to clear the queryCache entirely and start fresh.

```js
import { queryCache } from 'react-query'

queryCache.clear()
```

Expand All @@ -672,20 +657,7 @@ queryCache.clear()

## `makeQueryCache`

`makeQueryCache` creates an empty `queryCache` manually. This is useful together with `ReactQueryCacheProvider` to have multiple caches in your application.

As opposed to the global cache, caches created by `makeQueryCache` caches data even on the server.

```js
import { makeQueryCache } from 'react-query'

const queryCache = makeQueryCache()
```

**Returns**

- `queryCache: QueryCache`
- An empty `queryCache`
The `makeQueryCache` factory function has been deprecated in favor of `new QueryCache()`.

## `useQueryCache`

Expand All @@ -697,8 +669,6 @@ import { useQueryCache } from 'react-query'
const queryCache = useQueryCache()
```

If you are using the `ReactQueryCacheProvider` to set a custom cache, you cannot simply import `{ queryCache }` any more. This hook will ensure you're getting the correct instance.

## `useIsFetching`

`useIsFetching` is an optional hook that returns the `number` of the queries that your application is loading or fetching in the background (useful for app-wide loading indicators).
Expand Down Expand Up @@ -772,12 +742,12 @@ function App() {

## `ReactQueryCacheProvider`

`ReactQueryCacheProvider` is an optional provider component for explicitly setting the query cache used by React Query. This is useful for creating component-level caches that are not completely global, as well as making truly isolated unit tests.
The query cache can be connected to React with the `ReactQueryCacheProvider`. This component puts the cache on the context, which enables you to access it from anywhere in your component tree.

```js
import { ReactQueryCacheProvider, makeQueryCache } from 'react-query'
import { ReactQueryCacheProvider, QueryCache } from 'react-query'

const queryCache = makeQueryCache()
const queryCache = new QueryCache()

function App() {
return (
Expand All @@ -791,8 +761,7 @@ function App() {
**Options**

- `queryCache: QueryCache`
- In instance of queryCache, you can use the `makeQueryCache` factory to create this.
- If not provided, a new cache will be generated.
- Instance of QueryCache.

## `ReactQueryErrorResetBoundary`

Expand Down
4 changes: 3 additions & 1 deletion docs/src/pages/docs/guides/invalidations-from-mutations.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@ const [mutate] = useMutation(postTodo)
When a successful `postTodo` mutation happens, we likely want all `todos` queries to get invalidated and possibly refetched to show the new todo item. To do this, you can use `useMutation`'s `onSuccess` options and the `queryCache`'s `invalidateQueries` function:

```js
import { useMutation, queryCache } from 'react-query'
import { useMutation, useQueryCache } from 'react-query'

const queryCache = useQueryCache()

// When this mutation succeeds, invalidate any queries with the `todos` or `reminders` query key
const [mutate] = useMutation(addTodo, {
Expand Down
4 changes: 0 additions & 4 deletions docs/src/pages/docs/guides/prefetching.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,6 @@ title: Prefetching
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:

```js
import { queryCache } from 'react-query'

const prefetchTodos = async () => {
const queryData = await queryCache.prefetchQuery('todos', () =>
fetch('/todos')
Expand All @@ -25,7 +23,5 @@ If a prefetched query is rendered after the `staleTime` for a prefetched query,
Alternatively, if you already have the data for your query synchronously available, you don't need to prefetch it. You can just use the [Query Cache's `setQueryData` method](../api/#querycachesetquerydata) to directly add or update a query's cached result.

```js
import { queryCache } from 'react-query'

queryCache.setQueryData('todos', todos)
```
7 changes: 4 additions & 3 deletions docs/src/pages/docs/guides/query-invalidation.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,6 @@ title: Query Invalidation
Waiting for queries to become stale before they are fetched again doesn't always work, especially when you know for a fact that a query needs to get refetched. For that purpose, the `queryCache` has an `invalidateQueries` method that lets you manually mark queries as stale and potentially refetch them too!

```js
import { queryCache } from 'react-query'

queryCache.invalidateQueries('todos')
```

Expand All @@ -25,7 +23,10 @@ When using APIs like `invalidateQueries` and `removeQueries` (and others that su
In this example, we can use the `todos` prefix to invalidate any queries that start with `todos` in their query key:

```js
import { queryCache, useQuery } from 'react-query'
import { useQuery, useQueryCache } from 'react-query'

// Get QueryCache from the context
const queryCache = useQueryCache()

queryCache.invalidateQueries('todos')

Expand Down
41 changes: 23 additions & 18 deletions docs/src/pages/docs/guides/ssr.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,12 +59,14 @@ To support caching queries on the server and set up hydration, you start with wr

```jsx
// _app.jsx
import { ReactQueryCacheProvider } from 'react-query'
import { ReactQueryCacheProvider, QueryCache } from 'react-query'
import { Hydrate } from 'react-query/hydration'

const queryCache = new QueryCache()

export default function MyApp({ Component, pageProps }) {
return (
<ReactQueryCacheProvider>
<ReactQueryCacheProvider queryCache={queryCache}>
<Hydrate state={pageProps.dehydratedState}>
<Component {...pageProps} />
</Hydrate>
Expand All @@ -77,11 +79,11 @@ Now you are ready to prefetch some data in your pages with either [`getStaticPro

```jsx
// pages/posts.jsx
import { makeQueryCache } from 'react-query'
import { QueryCache } from 'react-query'
import { dehydrate } from 'react-query/hydration'

export async function getStaticProps() {
const queryCache = makeQueryCache()
const queryCache = new QueryCache()

await queryCache.prefetchQuery('posts', getPosts)

Expand Down Expand Up @@ -116,37 +118,38 @@ Since there are many different possible setups for SSR, it's hard to give a deta
> 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.

- Prefetch data
- Create a `prefetchQueryCache` specifically for prefetching by calling `const prefetchQueryCache = makeQueryCache()`
- Create a `prefetchQueryCache` specifically for prefetching by calling `const prefetchQueryCache = new QueryCache()`
- Call `prefetchQueryCache.prefetchQuery(...)` to prefetch queries
- Dehydrate by using `const dehydratedState = dehydrate(prefetchQueryCache)`
- Render
- Wrap the app in `<ReactQueryCacheProvider>` and `<Hydrate>` to create a new cache and hydrate the state
- This makes sure a separate `queryCache` is created specifically for rendering
- **Do not** pass in the `prefetchQueryCache` from the last step, 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.
- Create a new render query cache and hydrate the state. Use this query cache to render your app.
- **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.
- Serialize and embed `dehydratedState` in the markup
- 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)

**Client side**

- Parse `dehydratedState` from where you put it in the markup
- Create a cache and hydrate the state
- Render
- Wrap the app in `<Hydrate>` from `'react-query/hydration'` and pass in the dehyrated state.

This list aims to be exhaustive, but depending on your current setup, the above steps can take more or less work. Here is a barebones example:

```jsx
// Server
const prefetchCache = makeQueryCache()
const prefetchCache = new QueryCache()
await prefetchCache.prefetchQuery('key', fn)
const dehydratedState = dehydrate(prefetchCache)

const renderCache = new QueryCache()
hydrate(renderCache, dehydratedState)

const html = ReactDOM.renderToString(
<ReactQueryCacheProvider>
<Hydrate state={dehyratedState}>
<App />
</Hydrate>
<ReactQueryCacheProvider queryCache={renderCache}>
<App />
</ReactQueryCacheProvider>
)

res.send(`
<html>
<body>
Expand All @@ -160,11 +163,13 @@ res.send(`

// Client
const dehydratedState = JSON.parse(window.__REACT_QUERY_INITIAL_QUERIES__)

const queryCache = new QueryCache()
hydrate(queryCache, dehydratedState)

ReactDOM.hydrate(
<ReactQueryCacheProvider>
<Hydrate state={dehyratedState}>
<App />
</Hydrate>
<ReactQueryCacheProvider queryCache={queryCache}>
<App />
</ReactQueryCacheProvider>
)
```
Expand Down
12 changes: 11 additions & 1 deletion docs/src/pages/docs/overview.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,9 +47,19 @@ In the example below, you can see React Query in its most basic and simple form
[Open in CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-query/tree/master/examples/simple)

```js
import { useQuery } from 'react-query'
import { useQuery, QueryCache, ReactQueryCacheProvider } from 'react-query'

const queryCache = new QueryCache()

export default function App() {
return (
<ReactQueryCacheProvider queryCache={queryCache}>
<Example />
</ReactQueryCacheProvider>
)
}

function Example() {
const { isLoading, error, data } = useQuery('repoData', () =>
fetch('https://api.github.com/repos/tannerlinsley/react-query').then(res =>
res.json()
Expand Down
Loading