I use React + Redux + Webpack + WebpackDevserver. Once the hot loader is launched all my reducers are reseted to the initial state.
Can I keep somehow my reducers in the actual state?
My Webpack config contains:
entry: [ "./index.jsx" ], output: { filename: "./bundle.js" }, module: { loaders: [ { test: /\.js|\.jsx$/, exclude: /node_modules/, loaders: ["react-hot","babel-loader"], } ] }, plugins: [ new webpack.HotModuleReplacementPlugin() ]
My reducers stats with:
const initialState = { ... } export default function config(state = initialState, action) { ...
I start my Webpack Dev-Server just by:
"start": "webpack-dev-server",
When we refresh page in a web-app, the state always resets back to the initial values which in not a good thing when you try to build some large web-app like e-commerce. We can manually do the state persistent using the native JavaScript localStorage.
If you would like to persist your redux state across a browser refresh, it's best to do this using redux middleware. Check out the redux-persist and redux-storage middleware. They both try to accomplish the same task of storing your redux state so that it may be saved and loaded at will.
redux-persist gives us an ability to save Redux store in the Local Storage of the browser. Effectively, when you press the refresh page button in your browser, your storage will remain the same. Obviously, you can define how many levels or which parts of your store you want to make persistent.
To use the reducer function along with React we need to call it with one of the constants we setup, and then pass it into setState . increment = () => { this. setState( reducer({ type: INCREMENT, }) ); }; decrement = () => { this. setState( reducer({ type: DECREMENT, }) ); };
Assuming Babel 6, you need to do something along this:
import {createStore} from 'redux'; import rootReducer from '../reducers'; export default function configureStore(initialState) { const store = createStore(rootReducer, initialState); if(module.hot) { // Enable Webpack hot module replacement for reducers module.hot.accept('../reducers', () => { const nextReducer = require('../reducers/index').default; store.replaceReducer(nextReducer); }); } return store; }
You can see the approach in action at my redux demo.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With