I've created an app with Create-React-App and hot reloading is working, however the Redux state is lost. If I edit any component, e.g. to change a title, the state is lost - most annoying is that the user is logged out because the token stored in the state is lost. I've followed various examples including (https://redux.js.org/recipes/configuring-your-store) and can't figure out what's wrong here.
Any ideas what I've missed? Thank you!
index.js
const renderApp = () => {
ReactDOM.render(
<App />, document.getElementById('root')
);
};
if (process.env.NODE_ENV !== 'production' && module.hot) {
module.hot.accept('./App', renderApp);
}
renderApp();
store.js
const inititalState = {};
const store = createStore(
rootReducer,
inititalState,
compose(applyMiddleware(thunk),
window.__REDUX_DEVTOOLS_EXTENSION__&& window.__REDUX_DEVTOOLS_EXTENSION__()));
if (process.env.NODE_ENV !== 'production' && module.hot) {
module.hot.accept('./reducers', () => store.replaceReducer(rootReducer));
}
export default store;
reducers/index.js
import { combineReducers } from 'redux';
import errorReducer from './errorReducer';
import authReducer from './authReducer';
export default combineReducers({
'errors': errorReducer,
'auth': authReducer,
});
App.js:
class App extends Component {
render() {
return (
<Provider store = { store }>
<Router>
<div>
<Navbar />
<Route exact path="/" component={ Home } />
<div className="container">
<Route exact path="/register" component={ Register } />
<Route exact path="/login" component={ Login } />
<Route exact path="/forgotpassword" component={ ForgotPassword } />
</div>
</div>
</Router>
</Provider>
);
}
}
export default App;
From package.json:
"dependencies": {
"bootstrap": "^4.2.1",
"classnames": "^2.2.6",
"jquery": "^3.3.1",
"jwt-decode": "^2.2.0",
"react": "^16.7.0",
"react-dom": "^16.7.0",
"react-redux": "^6.0.0",
"react-router-dom": "^4.3.1",
"react-scripts": "2.1.2",
"reactstrap": "^7.0.2",
"redux": "^4.0.1",
"redux-thunk": "^2.3.0",
"updeep": "^1.1.0"
},
With the Redux Persist library, developers can save the Redux store in persistent storage, for example, the local storage. Therefore, even after refreshing the browser, the site state will still be preserved.
React Native solves this problem for the developers. Hot reloading allows you to see the changes that you have made in the code without reloading your entire app. Whenever you make any changes, all you need to do is save your code.
If you only need to save the token you could use the localstorage, if you want to save a lot of data you should take a look at redux-persist.
Example on saving using localStorage:
localStorage.setItem(token, res.data.token);
Example on retrieving using localStorage:
localStorage.getItem(token);
Example on removing the token if the user logs out:
localStorage.removeItem(token);
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