Reset to initial data in redux store

Weerapat Chulaket
MFEC
Published in
2 min readDec 16, 2018

--

Due to writing the web application using javascript framework like ReactJS, it’s usually a modularity which separates component in to multi files. Therefore it needs to send data to another components.

But if our application is larger. We therefore need some libs for help us to manage data in our application to centralize. In react called Redux.

All data in redux store will be cleared to initial state when client refresh our application on the browser or close the browser’s tab. So if our application have about user permission, role or something that for protected data. If you store that data in to redux store when you login with root access then you logout or switch to account that user permission or lower than root but you didn’t clear data in redux store. In this case, it’ll make lower permission can view your data because it stored in redux.

Let’s solve it.

In /reducers/index.js or some path that direct to your root reducers.

Before

import { combineReducers } from "redux";export default combineReducers({
state: (state = {}) => state
});

After

import { combineReducers } from "redux";
import { DESTROY_SESSION } from "../actions/types";
// Combine all reducers.
const appReducer = combineReducers({
state: (state = {}) => state
});
const rootReducer = (state, action) => {
// Clear all data in redux store to initial.
if(action.type === DESTROY_SESSION)
state = undefined;

return appReducer(state, action);
};
export default rootReducer;

Usage

In this case, I’ll example with onLogout() .

import { DESTROY_SESSION } from "./types";export const onLogout = () => {
return dispatch => {
// Your code here...
dispatch({ type: DESTROY_SESSION });
};
}

See this repository https://github.com/Keroro2139/clear-state-redux.

Hope that will be useful for everyone. Thank you.

Writer By Mr.Weerapat Chulaket — MFEC PEOPLE

--

--