Redux - Register a Store Listener

Hello there is a reducer function which takes state and action as an argument it’s okay but when you subscribe to store for listening count value in the store and reducer doesn’t have any relationship for count. Why is it needed ?

const ADD = 'ADD';

const reducer = (state = 0, action) => {
  switch(action.type) {
    case ADD:
      return state + 1;
    default:
      return state;
  }
};

const store = Redux.createStore(reducer);

// Global count variable:
let count = 0;

// Change code below this line
store.subscribe(() => count++)
// Change code above this line

store.dispatch({type: ADD});
console.log(count);
store.dispatch({type: ADD});
console.log(count);
store.dispatch({type: ADD});
console.log(count);

Challenge: Redux - Register a Store Listener

Link to the challenge:

It is just illustrating how the subscriber function is called after each dispatch, there is no relation. A more clear example might have been a console.log and a state getter.

const ADD = 'ADD';

const reducer = (state = 0, action) => {
  switch(action.type) {
    case ADD:
      return state + 1;
    default:
      return state;
  }
};

const store = Redux.createStore(reducer);

// Global count variable:
let count = 0;

// Change code below this line
store.subscribe(() => console.log('dispatch called'))
// Change code above this line

console.log('state is', store.getState());
store.dispatch({type: ADD});
console.log('state is', store.getState());
store.dispatch({type: ADD});
console.log('state is', store.getState());
store.dispatch({type: ADD});
console.log('state is', store.getState());

Logs

state is 0
dispatch called
state is 1
dispatch called
state is 2
dispatch called
state is 3

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.