Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redux - how to keep the reducer state during hot reload

Tags:

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", 
like image 374
Tomas Randus Avatar asked Jan 07 '16 12:01

Tomas Randus


People also ask

Does Redux state persist on refresh?

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.

How do I keep Redux state?

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.

How do you persist Redux toolkit?

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.

How do you set state in reducer?

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, }) ); };


1 Answers

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.

like image 197
Juho Vepsäläinen Avatar answered Oct 13 '22 11:10

Juho Vepsäläinen