Skip to content

Commit

Permalink
Merge pull request #3948 from reduxjs/extractrehydrationinfo-circular
Browse files Browse the repository at this point in the history
  • Loading branch information
markerikson committed Dec 5, 2023
2 parents cf29e62 + 92c529c commit 5eb3680
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 7 deletions.
17 changes: 11 additions & 6 deletions docs/rtk-query/usage/persistence-and-rehydration.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -37,28 +37,33 @@ box with the `autoMergeLevel1` or `autoMergeLevel2` [state reconcilers](https://
when persisting the root reducer, or with the `autoMergeLevel1` reconciler when persisting just the api reducer.

```ts title="redux-persist rehydration example"
import type { Action, PayloadAction } from '@reduxjs/toolkit'
import type { Action } from '@reduxjs/toolkit'
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
import { REHYDRATE } from 'redux-persist'

type RootState = any // normally inferred from state

function isHydrateAction(action: Action): action is PayloadAction<RootState> {
function isHydrateAction(action: Action): action is Action<typeof REHYDRATE> & {
key: string
payload: RootState
err: unknown
} {
return action.type === REHYDRATE
}

export const api = createApi({
baseQuery: fetchBaseQuery({ baseUrl: '/' }),
// highlight-start
extractRehydrationInfo(action, { reducerPath }) {
// to prevent circular type issues, the return type needs to be annotated as any
extractRehydrationInfo(action, { reducerPath }): any {
if (isHydrateAction(action)) {
if ((action as any).key === 'key used with redux-persist') {
// when persisting the api reducer
// when persisting the api reducer
if (action.key === 'key used with redux-persist') {
return action.payload
}

// When persisting the root reducer
return action.payload[reducerPath]
return action.payload[api.reducerPath]
}
},
// highlight-end
Expand Down
2 changes: 1 addition & 1 deletion packages/toolkit/src/query/createApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ export interface CreateApiOptions<
* export const api = createApi({
* baseQuery: fetchBaseQuery({ baseUrl: '/' }),
* // highlight-start
* extractRehydrationInfo(action, { reducerPath }) {
* extractRehydrationInfo(action, { reducerPath }): any {
* if (isHydrateAction(action)) {
* return action.payload[reducerPath]
* }
Expand Down

0 comments on commit 5eb3680

Please sign in to comment.