I'm learning Redux and I have a doubt when I apply in this simple example:
const redux = require('redux');
const counterReducer = (state = { counter: 0 }, action) => {
if (action.type === 'increment') {
return {
counter: state.counter + 1,
};
}
if (action.type === 'decrement') {
return {
counter: state.counter - 1,
};
}
return state;
};
const store = redux.createStore(counterReducer);
const counterSubscriber = () => {
const latestState = store.getState();
console.log(latestState);
};
store.subscribe(counterSubscriber);
store.dispatch({ type: 'increment' });
store.dispatch({ type: 'decrement' });
I get as a result:
{ counter: 1 }
{ counter: 0 }
But you shouldn't get:
{ counter: 1 }
{ counter: -1 }
Because the state starts at 0 state = { counter: 0 }
. So when calling increment
add 1 and decrement
subtract 1?
Methods
dispatch
behave like any other function in JavaScript , they are executed in sequence.That said, and following the OP's code sequence, it first runs:
The initial state is
state = { counter: 0 }
:Then, the
store
helps us to persist the value changes in the state, so at the time of invoking:The state is
state = { counter: 1 }
:The method may also be confusing
subscribe
, since it is declared before the method invocationdispatch
:Just remember that this method asks for a function that will be called immediately after each
dispatch
.In this case, the function that is going to be called after each dispatch is
counterSubscriber
, which is where the status changes are being monitored by console.Hope this answer is helpful.