Skip to content

Instantly share code, notes, and snippets.

@furugomu
Created November 29, 2018 08:25
Show Gist options
  • Save furugomu/0224e0fc1108c6a446d71086dc5e2a93 to your computer and use it in GitHub Desktop.
Save furugomu/0224e0fc1108c6a446d71086dc5e2a93 to your computer and use it in GitHub Desktop.
store の中身を localStorage に保存するやつ
import { StoreEnhancer } from "redux";
/**
* 最初に localStorage から取ってきて
* dispatch 毎に localStorage に保存する
* @usage
* createStore(reducer, localStorageEnhancer('unko'))
* createStore(reducer, compose(applyMiddleware(...), localStorageEnhancer('unko')))
*/
const enhancer = (key: string): StoreEnhancer => {
return next => (reducer, preloadedState) => {
const savedState: {} = JSON.parse(localStorage.getItem(key) || "{}");
const state = { ...savedState, ...(preloadedState as {}) };
const store = next(reducer, state);
store.subscribe(() => {
localStorage.setItem(key, JSON.stringify(store.getState()));
});
return store;
};
};
export default enhancer;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment