Magnum
Magnum

Reputation: 2395

Redux - Reset state of subtree

What is the proper way to reset the subtree of a redux store? I'm not interested in resetting the entire redux store, but just the reducer subtree portion of it.

Here is an example snippet:

//initial state
const initialState = {
    isFetching: false,
    error: '',
    page: 0
}

//reducer for suggestions store
export default function suggestions (state = initialState, action) {
    switch (action.type) {
        case FETCHING_SUGGESTIONS : {
            return {
                ...state,
                isFetching: true
            }
        }
        case FETCHING_SUGGESTIONS_SUCCESS : {
            return {
                ...state,
                [action.suggestion.suggestionId] : action.suggestion
            }
        }
        case FETCHING_SUGGESTIONS_ERROR : {
            return {
                ...state,
                isFetching: false,
                error: "Error in fetching suggestions"
            }
        }
        case CHANGE_PAGE : {
            return {
                ...state,
                page: action.page
            }
        }
        case ADD_SUGGESTION : {
            return {
                ...state,
                [action.suggestion.suggestionId]: action.suggestion
            }
        }
        case CLEAR_SUGGESTIONS : {
            return {
                initialState
            }
        }
        default : 
            return state
    }
}

I would think this would work, however whenever the CLEAR_SUGGESTIONS action is dispatched, I suddenly get undefined props in some of my components and the following error: warning.js:36 Warning: performUpdateIfNecessary: Unexpected batch number (current 161, pending 157)

I'm not 100% confident I'm doing this correctly. Can someone confirm if the issue is with my reducer, or somewhere along my components lifecycle methods?

Thanks!

Upvotes: 0

Views: 1693

Answers (2)

TomW
TomW

Reputation: 4002

You are accidentally nesting initialState under a key called 'initialState. You just want:

case CLEAR_SUGGESTIONS : {
  return initialState
}

There's no need to copy initialState, since store state is immutable.

Upvotes: 1

tobiasandersen
tobiasandersen

Reputation: 8680

The object you create will look like this:

{
  initialState: {
    isFetching: false,
    error: '',
    page: 0
  }
}

What you want is this:

case CLEAR_SUGGESTIONS : {
  return {
    ...initialState
  }
}

Upvotes: 1

Related Questions