ストア永続化
reduxではストアがグローバル管理されているので、永続化も簡単です。
加えて、redux-percistを使うとさらに簡単に永続化ができます。
https://github.com/rt2zz/redux-persist
以下はReact Nativeでの例ですが、もちろんstorageを変更することでReactJSでも利用できます。
導入方法
configureStore.jsを作成
import { createStore, compose, applyMiddleware } from 'redux';
import { persistStore, persistCombineReducers } from 'redux-persist';
import AsyncStorage from '@react-native-community/async-storage';
import { createLogger } from 'redux-logger';
import rootReducers from 'app/reducers'; // where reducers is a object of reducers
const config = {
// 保存データのrootキー
key: 'root',
// React NativeなのでAsyncStorageを使用
storage: AsyncStorage,
// loadingReducerは保存しないようにする、whitelistも可能
blacklist: ['loadingReducer'],
debug: true, //to get useful logging
};
const middleware = [];
if (__DEV__) {
middleware.push(createLogger());
}
const reducers = persistCombineReducers(config, rootReducers);
const enhancers = [applyMiddleware(...middleware)];
const persistConfig = { enhancers };
const store = createStore(reducers, undefined, compose(...enhancers));
const persistor = persistStore(store, persistConfig, () => {
console.log('テスト', store.getState());
});
const configureStore = () => {
return { persistor, store };
};
export default configureStore;
エントリポイントをPersistGateでラップする
import React from 'react';
import { ActivityIndicator } from 'react-native';
import { Provider } from 'react-redux';
import { PersistGate } from 'redux-persist/es/integration/react';
import Navigator from 'app/navigation';
import configureStore from 'app/store/configureStore';
const { persistor, store } = configureStore();
export default function Entrypoint() {
return (
<Provider store={store}>
<PersistGate loading={<ActivityIndicator />} persistor={persistor}>
<Navigator />
</PersistGate>
</Provider>
);
}
データの削除
persistor.purge()で永続化されたデータを削除できます。
マイグレーション
ストアの構造が変わることを想定して、schemaVersionなどを設定しておくと便利。
const schemaVersion = persistConfig.schemaVersion;
AsyncStorage.getItem('schemaVersion').then((localSchemaVersion) => {
const schemaUpdated = localSchemaVersion !== schemaVersion;
if (schemaUpdated) {
persistStore(store, config, callback).purge();
AsyncStorage.setItem('schemaVersion', schemaVersion);
return;
}
persistStore(store, config, callback);
}).catch(() => {
persistStore(store, config, callback);
AsyncStorage.setItem('schemaVersion', schemaVersion);
});
まとめ
そのままStoreを保存しておいてくれるのでとても便利。