-
Notifications
You must be signed in to change notification settings - Fork 62
Persistence
Daishi Kato edited this page Mar 17, 2019
·
1 revision
If you want to persist and rehydrate changes of the state. Full Example
- Define a storage key
const persistenceKey = 'my_cool_app_persistence'
- Replace Reducer This will save the changes into localstorage.
// Before
export const { GlobalStateProvider, dispatch, useGlobalState } = createStore(myReducer, initialState)
// After
const persistentReducer = (state, action) => {
const mutated = myReducer(state, action)
localStorage.setItem(persistenceKey, JSON.stringify(mutated))
return mutated
}
export const { GlobalStateProvider, dispatch, useGlobalState } = createStore(persistentReducer, initialState)
- Rehydrate on startup
// Before
const initialState = { counter: 0 }
// After
const firstState = { counter: 0 }
const initialStringFromStorage = localStorage.getItem(persistenceKey)
const initialState = initialStringFromStorage === null
? firstState
: JSON.parse(initialStringFromStorage)
Done 🚀