LoginSignup
0
0

More than 1 year has passed since last update.

React-Native > Redux > redux-percist ストアを永続化

Posted at

ReduxのStoreを永続化するライブラリ redux-persist

環境

以下が適用済み

  • redux
  • reudx-toolkit

package

yarn add @react-native-async-storage/async-storage
yarn add redux-persist

PersistGate

App.ts

PersistGateでラップする

App.tsx
import { PersistGate } from 'redux-persist/integration/react'

import { store, persistor } from './configureStore';


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

configureStore.js

configureStore.js
// configureStore.js

import { createStore } from 'redux'
import { persistStore, persistReducer } from 'redux-persist'
import AsyncStorage from '@react-native-async-storage/async-storage';


import rootReducer from './reducers'

// 将来的にStoreの構成が変わったときにMigrationする際に使う
const migrations = {
  1: (state) => {
    // migration to keep only etc.
    return {
      ...state,
    };
  },
};

// persistReducerに渡すためのpersistConfig
const persistConfig = {
  key: 'root',
  version: 1, // Storeの構成が変わったときにはversion no.を上げる
  storage: AsyncStorage,
  migrate: createMigrate(migrations, { debug: false }),
};



const persistedReducer = persistReducer(persistConfig, rootReducer)


export const store = createStore(persistedReducer);
export const persistor = persistStore(store);

export type RootState = ReturnType<typeof store.getState>;
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0