メインコンテンツへスキップ

永続化とリハイドレーション

RTK Queryは、createApiextractRehydrationInfoオプションを介してリハイドレーションをサポートします。この関数には、ディスパッチされたすべてのアクションが渡され、undefined以外の値を返す場合、その値は完了およびエラーが発生したクエリのAPI状態をリハイドレートするために使用されます。

サーバーサイドレンダリングも参照してください。

情報

一般的に、APIスライスの永続化は推奨されず、代わりに、ブラウザでキャッシュの挙動を定義するために、Cache-Controlヘッダーのようなメカニズムを使用する必要があります。APIスライスを永続化してリハイドレートすると、ユーザーがしばらくページにアクセスしていない場合、常に非常に古いデータが残る可能性があります。それにもかかわらず、これを処理するブラウザキャッシュがないネイティブアプリのような環境では、永続化が実行可能なオプションになる可能性があります。

Redux Persist

API状態のリハイドレーションは、redux-persistからインポートされたREHYDRATEアクションタイプを活用することにより、Redux Persistと組み合わせて使用できます。これは、ルートリデューサーを永続化する際にautoMergeLevel1またはautoMergeLevel2ステートリコンサイラーを使用するか、APIリデューサーのみを永続化する際にautoMergeLevel1リコンサイラーを使用すると、すぐに使用できます。

redux-persistリハイドレーションの例
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 Action<typeof REHYDRATE> & {
key: string
payload: RootState
err: unknown
} {
return action.type === REHYDRATE
}

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

// When persisting the root reducer
return action.payload[api.reducerPath]
}
},
endpoints: (build) => ({
// omitted
}),
})