Reputation: 109
I am running a simple Redux reducer and store, but for some reason the reducer is called by default. Is that normal?
const apiWrapper = (state = {}, action) => {
switch(action.type) {
case "HELLO":
console.log("hello");
return state;
break;
default:
console.log("default");
}
}
const { createStore } = Redux;
const store = createStore(apiWrapper);
store.dispatch({ type: "HELLO" });
The snippet above outputs:
"default"
"hello"
I am only expecting it to log hello
, why is default
there too? Here's a JSBin.
Upvotes: 3
Views: 1030
Reputation: 57964
Redux internally dispatches a dummy action when creating the store in order to set up the initial state. Per the Redux documentation:
When a store is created, Redux dispatches a dummy action to your reducer to populate the store with the initial state. You are not meant to handle the dummy action directly. Just remember that your reducer should return some kind of initial state if the state given to it as the first argument is undefined, and you're all set.
So when your reducer is first called, state
will be undefined thus your default value {}
will be used. Also, it will go to the default
case because you're not supposed to explicitly handle the action, and thus you get the console.log
. Make sure to return the state in the default
case to set up initial state correctly.
Just out of curiosity, the action type the first dummy call Redux does is "@@redux/INIT"
signifying that Redux is initializing the store and testing it. A similar thing happens with combineReducers
to test for bad patterns in reducers. Specifically, in the source:
// When a store is created, an "INIT" action is dispatched so that every // reducer returns their initial state. This effectively populates // the initial state tree. dispatch({ type: ActionTypes.INIT })
So the initial dispatch essentially gives each reducer its respective slice of state, and populates the initial state tree.
Upvotes: 8