-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
📝 Document SSR & persistence/rehydration related features #1639
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
phryneas
merged 9 commits into
reduxjs:v1.7.0-integration
from
Shrugsy:docs/ssr-suspense
Oct 29, 2021
Merged
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
8036582
📝 Update cache management utils in overview
Shrugsy 3632213
📝 Document SSR related features
Shrugsy 639c1f1
📝 Document persistence related features
Shrugsy a7faabb
📝 Update `extractRehydrationInfo` documentation
Shrugsy e229586
📝 Update various ssr/rehydration documentation
Shrugsy 0ca9b98
📝 Remove redundancy
Shrugsy 55560b2
📝 Merge API slice util docs
Shrugsy 0e7c9a6
📝 Expand `getRunningOperationPromise` description
Shrugsy a04208e
Apply suggestions from code review
phryneas File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,56 @@ | ||
--- | ||
id: persistence-and-rehydration | ||
title: Persistence and Rehydration | ||
sidebar_label: Persistence and Rehydration | ||
hide_title: true | ||
description: 'RTK Query > Usage > Persistence and Rehydration' | ||
--- | ||
|
||
| ||
|
||
# Persistence and Rehydration | ||
|
||
RTK Query supports rehydration via the [`extractRehydrationInfo`](../api/createApi.mdx#extractrehydrationinfo) | ||
option on [`createApi`](../api/createApi.mdx). This function is passed every dispatched action, | ||
and where it returns a value other than `undefined`, that value is used to rehydrate the API state | ||
for fulfilled & errored queries. | ||
|
||
See also [Server Side Rendering](./server-side-rendering.mdx). | ||
|
||
:::info | ||
|
||
Generally, persisting API slices is not recommended and instead, mechanisms like | ||
[`Cache-Control` Headers](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control) | ||
should be used in browsers to define cache behaviour. | ||
Persisting and rehydrating an api slice might always leave the user with very stale data if the user | ||
has not visited the page for some time. | ||
Nonetheless, in environments like Native Apps, where there is no browser cache to take care of this, | ||
persistance might still be a viable option. | ||
|
||
::: | ||
|
||
## Redux Persist | ||
|
||
API state rehydration can be used in conjunction with [Redux Persist](https://github.com/rt2zz/redux-persist) | ||
by leveraging the `REHYDRATE` action type imported from `redux-persist`. This can be used out of the | ||
box with the `autoMergeLevel1` or `autoMergeLevel2` [state reconcilers](https://github.com/rt2zz/redux-persist#state-reconciler) | ||
when persisting the root reducer, or with the `autoMergeLevel1` reconciler when persisting just the api reducer. | ||
|
||
```ts title="redux-persist rehydration example" | ||
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react' | ||
import { REHYDRATE } from 'redux-persist' | ||
|
||
export const api = createApi({ | ||
baseQuery: fetchBaseQuery({ baseUrl: '/' }), | ||
// highlight-start | ||
extractRehydrationInfo(action, { reducerPath }) { | ||
if (action.type === REHYDRATE) { | ||
return action.payload[reducerPath] | ||
} | ||
}, | ||
// highlight-end | ||
endpoints: (build) => ({ | ||
// omitted | ||
}), | ||
}) | ||
``` |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,59 @@ | ||
--- | ||
id: server-side-rendering | ||
title: Server Side Rendering | ||
sidebar_label: Server Side Rendering | ||
hide_title: true | ||
description: 'RTK Query > Usage > Server Side Rendering' | ||
--- | ||
|
||
| ||
|
||
# Server Side Rendering | ||
|
||
## Server Side Rendering with Next.js | ||
|
||
RTK Query supports Server Side Rendering (SSR) with [Next.js](https://nextjs.org/) via | ||
[rehydration](./persistence-and-rehydration.mdx) in combination with | ||
[next-redux-wrapper](https://github.com/kirill-konshin/next-redux-wrapper). | ||
|
||
The workflow is as follows: | ||
|
||
- Set up `next-redux-wrapper` | ||
- In `getStaticProps` or `getServerSideProps`: | ||
- Pre-fetch all queries via the `initiate` actions, e.g. `store.dispatch(api.endpoints.getPokemonByName.initiate(name))` | ||
- Wait for each query to finish using `await Promise.all(api.getRunningOperationPromises())` | ||
- In your `createApi` call, configure rehydration using the `extractRehydrationInfo` option: | ||
|
||
[examples](docblock://query/createApi.ts?token=CreateApiOptions.extractRehydrationInfo) | ||
|
||
An example repo using `next.js` is available [here](https://github.com/phryneas/ssr-experiments/tree/main/nextjs-blog). | ||
|
||
:::tip | ||
While memory leaks are not anticipated, once a render is sent to the client and the store is being | ||
removed from memory, you may wish to also call `store.dispatch(api.util.resetApiState())` to | ||
ensure that no rogue timers are left running. | ||
::: | ||
|
||
:::tip | ||
In order to avoid providing stale data with Static Site Generation (SSG), you may wish to set | ||
[`refetchOnMountOrArgChange`](../api/createApi.mdx#refetchonmountorargchange) to a reasonable value | ||
such as 900 (seconds) in order to allow data to be re-fetched when accessed if it has been that | ||
long since the page was generated. | ||
::: | ||
Comment on lines
+37
to
+42
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. @Ephem @phryneas FYI I've added this note to account for stale SSG data as per #1639 (comment) & #1639 (comment) |
||
|
||
## Server Side Rendering elsewhere | ||
|
||
If you are not using `next.js`, and the example above cannot be adapted to your SSR framework, | ||
an `unstable__` marked approach is available to support SSR scenarios where you need to execute | ||
async code during render and not safely in an effect. | ||
This is a similar approach to using [`getDataFromTree`](https://www.apollographql.com/docs/react/performance/server-side-rendering/#executing-queries-with-getdatafromtree) | ||
with [Apollo](https://www.apollographql.com/docs/). | ||
|
||
The workflow is as follows: | ||
|
||
- Create a version of `createApi` that performs asynchronous work during render: | ||
|
||
[examples](docblock://query/react/module.ts?token=ReactHooksModuleOptions.unstable__sideEffectsInRender) | ||
|
||
- Use your custom `createApi` when calling `const api = createApi({...})` | ||
- Wait for all queries to finish using `await Promise.all(api.getRunningOperationPromises())` before performing the next render cycle |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.