redux-persist with react-redux-starter-kit
Recently I’ve worked with react-redux-starter-kit and I needed to add redux-persist to save data between switching routes (walking through the webpage). Scenario was simple, load data from API – save it and on returning again to the page – load data from redux-store without calling an API – but on refreshing the page – call API to get new data.
In file src/store/createStore.js
import { autoRehydrate } from 'redux-persist';
// the do the createStore add
const store = createStore(
makeRootReducer(),
initialState,
composeEnhancers(
applyMiddleware(...middleware),
autoRehydrate(),
...enhancers
)
)
Next in file src/main.jsadd
import { persistStore } from 'redux-persist';
const initialState = window.___INITIAL_STATE__ const store = createStore(initialState) export const persist = persistStore(store);
than in any file (i.e. src/routes/Menu/modules/menu.js, where you want to use redux-persist you can use:
import { REHYDRATE } from 'redux-persist/constants'
//... some code
export default function appResources(state=initialState, action) {
switch(action.type) {
case SOME_DECLARED_CASE:
return Object.assign({}, state, { isInvalidated: true })
case REHYDRATE:
let incoming = action.payload.app_resources
if (incoming) {
return Object.assign({}, state, {
...incoming,
isBusy: false,
isInvalidated: true,
isFailed: false,
failedMessage: null,
isAppReady: true
});
}
return state;
default:
return state;
}
}
in src/routes/Menu/containers/Menu.js
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import * as appResourcesActions from '../modules/menu'
import MenuView from '../components/MenuView'
const mapDispatchToProps = (dispatch) => ({
appResourcesActions: bindActionCreators(appResourcesActions, dispatch)
})
const mapStateToProps = (state) => ({
app_resources : state.app_resources
})
export default connect(mapStateToProps, mapDispatchToProps)(MenuView)
and probably that’s how to configure redux-persist with react-redux-starer-kit – the most important thing is with main.js and createStore.js files – where you binding redux-persist with redux.
Cheers

Najnowsze komentarze