会員サイトでログアウトした場合などに、Reduxのstoreをリセットしたい。
リセットしないと、そのまま違うアカウントでログインしたときにいろいろ困る。
reducer単位でクリアするパターン
store.js
import { createStore, combineReducers } from "redux";
import a from "./reducers/a";
import b from "./reducers/b";
const rootReducer = combineReducers({
a,
b
});
export default createStore(rootreducer);
reducer/a.js
export const registerName = name => {
return {
type: "INSERT_NAME",
name: name
}
}
export const registerAge = age => {
return {
type: "INSERT_AGE",
age: age
}
}
// ここにクリアアクションを追加
export const clearState = () => {
return {
type: "CLEAR_STATE"
}
}
const initialState = { name: "", age: ""}
export default reducer(state = initialState, action) {
switch(action.type) {
case "INSERT_NAME":
return {
...state,
name: action.name
}
case "INSERT_AGE":
return {
...state,
age: action.age
}
case "CLEAR_STATE":
return initialState
default:
return state
}
}
reducer/b.jsでも同じことをする
stackoverflowにあったイケてるやつを参考にしたパターン
store.js
import { createStore, combineReducers } from "redux";
import a from "./reducers/a";
import b from "./reducers/b";
const appReducer = combineReducers({
a,
b
});
const rootReducer = (state, action) => {
if (action.type === "CLEAR_STATE") {
state = undefined;
}
return appReducer(state, action);
};
export default createStore(rootreducer);
素晴らしいね!!