24
23

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Redux】ストアの状態をリセットする

Last updated at Posted at 2018-01-29

会員サイトでログアウトした場合などに、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にあったイケてるやつを参考にしたパターン

参考: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);

素晴らしいね!!

24
23
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
24
23

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?