Created
November 29, 2018 08:25
-
-
Save furugomu/0224e0fc1108c6a446d71086dc5e2a93 to your computer and use it in GitHub Desktop.
store の中身を localStorage に保存するやつ
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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