redux-persist README

README проекта с github.com/endograph/redux-persist. Одним файлом markdown: README.md.

redux-persist

Quickstart · API · Storage engines · npm

redux-persist

CI npm npm next downloads license

Persist and rehydrate a redux store. Your state is saved to storage as it changes and restored into the store when your app starts.

Hey all! redux-persist is maintained again, and v7 is in beta (npm install redux-persist@next): Redux Toolkit 2 support with no extra setup, a fix for stored data getting wiped (#809), and lots more. Please try it and tell us how it goes in the v7 beta discussion.

These docs are for v7, which needs Redux 5 or Redux Toolkit 2. Upgrading from 6? Read the migration guide; your stored data carries over as is. For 6.x, see the v6 docs.

Quickstart

npm install redux-persist

Wrap your root reducer and create a persistor alongside the store:

// app/store.ts
import { configureStore, combineReducers } from '@reduxjs/toolkit'
import { persistStore, persistReducer } from 'redux-persist'
import storage from 'redux-persist/storage' // localStorage on the web
import userReducer from './features/user/userSlice'
import configReducer from './features/config/configSlice'

const rootReducer = combineReducers({
  user: userReducer,
  config: configReducer
})

const persistConfig = {
  key: 'root',
  version: 1,
  storage,
}

const persistedReducer = persistReducer(persistConfig, rootReducer)

export const store = configureStore({
  reducer: persistedReducer,
})

export const persistor = persistStore(store)

If you use React, wrap your root component in PersistGate. It holds off rendering until the stored state has been loaded back into redux. loading can be null or any React element, e.g. loading={<Loading />}.

import { PersistGate } from 'redux-persist/react'
import { store, persistor } from './app/store'

// ... normal setup, import components etc.

const App = () => {
  return (
    <Provider store={store}>
      <PersistGate loading={null} persistor={persistor}>
        <RootComponent />
      </PersistGate>
    </Provider>
  );
};

If you'd rather not gate rendering, useRehydrated(persistor) from redux-persist/react returns whether stored state has loaded.

Every app has to decide how many levels of stored state to merge into its initial state. The default is one level; read state reconcilers before you ship.

React Native

Pass your storage engine explicitly:

import AsyncStorage from '@react-native-async-storage/async-storage'

const persistConfig = {
  key: 'root',
  storage: AsyncStorage,
}

Server rendering

redux-persist/storage works during server rendering (Next.js and others): on the server it stores nothing, and stored state is loaded in the browser. With the Next.js App Router, render PersistGate from a Client Component; see PersistGate.

Choosing what's saved

denylist and allowlist pick top-level keys:

persistReducer({ key: 'root', storage, denylist: ['navigation'] }, rootReducer) // navigation will not be persisted

persistReducer({ key: 'root', storage, allowlist: ['navigation'] }, rootReducer) // only navigation will be persisted

They're checked against your state's keys, so a typo is a type error. If you declare the config separately, annotate it with PersistConfig<RootState> or use as const on the array. The older names blacklist and whitelist still work.

For keys you can't list ahead of time, pass a function that's called with each top-level key:

persistReducer({ key: 'root', storage, denylist: key => key.startsWith('temp') }, rootReducer) // keys starting with temp will not be persisted

To go deeper than one level, use nested persists.

Resetting state on logout

Reset state inside the reducer you pass to persistReducer, so the reset state is saved too:

const rootReducer = (state, action) =>
  appReducer(action.type === 'user/logout' ? undefined : state, action)

const persistedReducer = persistReducer(persistConfig, rootReducer)

The reset state is saved like any other change. To write it right away (for example before the app might close), await persistor.flush() after dispatching the action.

Don't reset above persistReducer (by wrapping the persisted reducer, or with a store enhancer that replaces the whole state): that removes the _persist key, so the state stops being saved, and the previous user's state is loaded again on the next launch. redux-persist logs an error in development when this happens.

Learn more

Contributing

Bug reports and pull requests are welcome; see CONTRIBUTING.md, especially before changing anything that touches stored data. Questions and feature ideas go in Discussions. Feedback on the v7 beta goes in the v7 beta discussion.

redux-persist (endograph/redux-persist)

Ищем в базе…

Что это такое?Redux Persist — это библиотека, которая сохраняет (persist) ваше хранилище Redux (store) в локальное хранилище и автоматически восстанавливает (rehydrate) его при перезагрузке приложения, чтобы состояние сохранялось после обновления страницы или перезапуска приложения.
Это библиотека, которую добавляют в уже существующее Redux-приложение, или самостоятельный инструмент?Это библиотека, которую устанавливают в уже готовое Redux-приложение: нужно обернуть редьюсер функцией persistReducer и вызвать persistStore для хранилища.
Как добавить её в проект?Установите командой npm install redux-persist, оберните корневой редьюсер в persistReducer(config, reducer), создайте persistor через persistStore(store) и, если нужно, оберните React-приложение в PersistGate, чтобы отложить отрисовку до завершения восстановления данных.
Нужен ли отдельный движок хранения или всё работает сразу?В комплекте есть движки localStorage и sessionStorage для веба, а также поддерживается большой список сторонних движков хранения (electron-store, react-native-fs, Expo filesystem/SecureStore, IndexedDB через localForage, PouchDB, Realm и другие), которые передаются в конфигурацию.
Какая главная ловушка при настройке?Нужно правильно выбрать алгоритм слияния состояния (state reconciler), то есть то, как сохранённое состояние объединяется с начальным состоянием редьюсера. По умолчанию объединение поверхностное и затрагивает только один уровень вложенности, поэтому, если быть невнимательным, вложенное состояние может молча потеряться.
Это работает только с React-приложениями?Нет, основная библиотека не привязана к фреймворку и работает с любым хранилищем Redux (в вебе или в React Native); PersistGate — это лишь необязательный удобный компонент для React.
Можно сохранять только часть состояния?Да, с помощью опций конфигурации whitelist и blacklist можно включать или исключать определённые ключи редьюсера, а также вкладывать persistReducer глубже для более тонкого контроля.
Как мигрировать сохранённое состояние, когда меняется структура данных?persistReducer принимает функцию migrate, которая выполняется над загруженным состоянием до слияния; redux-persist также включает createMigrate для создания синхронных миграций между версиями структуры состояния.
Можно ли преобразовывать данные перед сохранением, например сжимать или шифровать их?Да, Transforms позволяют изменять состояние непосредственно перед сохранением и сразу после восстановления; для сжатия (lz-string), шифрования AES и фильтрации части состояния существуют сторонние пакеты.
Что случилось с поддержкой проекта?В сентябре 2021 года проект передали новому мейнтейнеру, который разбирает задачи, обновляет зависимости и переводит кодовую базу с Flow на TypeScript и с Ava на Jest.
Какие есть похожие проекты?rxdb, Dexie.js, ultrastorage, redux, redux-toolkit, lowdb, WatermelonDB, zustand
Автор
endograph
Размер
1.4 MB
Звёзды
13K
Возраст
11 г
Коммиты · 90 дней