Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
21
Help us understand the problem. What is going on with this article?
@komakishunsuke

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

会員サイトでログアウトした場合などに、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);

素晴らしいね!!

21
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
21
Help us understand the problem. What is going on with this article?