LoginSignup
15
14

More than 5 years have passed since last update.

Redux Persistでローカルのストレージエンジンにstoreを永続化する

Last updated at Posted at 2018-01-03

概要

Redux Persistは、Reduxのstore永続化を簡単に行うことができるライブラリだ。アプリなどで、手軽にオフラインへのデータ保持を実装できる。

今回はその特徴を軽く紹介してみようと思う。

設定が容易

Redux Persistを使うと、storeの保持についての設計を考える必要がない。以下はほぼREADMEのサンプルだが、簡単な設定でReduxに組み込むことができる。

import { persistStore, persistCombineReducers } from 'redux-persist'
import storage from 'redux-persist/es/storage'
import reducers from './reducers'

const config = {
  key: 'root',
  storage,
}

const reducer = persistCombineReducers(config, reducers)

function configureStore () {
  // ...
  let store = createStore(reducer)
  let persistor = persistStore(store)

  return { persistor, store }
}

これだけでstoreがローカル環境に保持される。

クロスプラットフォーム

Redux Persistは各環境に合わせて、storeを保持する仕組みを変えることができる。

例えば、WebではデフォルトでlocalStorage、iOS(React Native)だとデフォルトでAsyncStorageが使用される。他にも、以下のようなストレージが使用可能だ。

細かいカスタマイズ

各stateによって、どのキーを保持するか/しないかなどを設定したいときがある(例えば、データをロード中、などの一時的な状態は保持したくない)。

そんなときは、blacklistwhiteliststateReconcilerなどで細かい調整ができる。

storeの構造を変えたい時

store構造の変更により、心当たりのないバグを生む場合がある。そういう時は、versionを指定しておいて、store構造を変えた際にアップデートすれば良い。

const reducerVersion = persistConfig.version;

AsyncStorage.getItem('reducerVersion').then((localVersion) => {
  const reducerUpdated = localVersion !== reducerVersion;
  if (reducerUpdated) {
    // ここで永続化したstoreをリセットしている。
    persistStore(store, config, callback).purge();
    AsyncStorage.setItem('reducerVersion', reducerVersion);
    return;
  }
  persistStore(store, config, callback);
}).catch(() => {
  persistStore(store, config, callback);
  AsyncStorage.setItem('reducerVersion', reducerVersion);
});

参考

15
14
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
15
14