DEV Community

Randy Rivera
Randy Rivera

Posted on • Edited on

Redux: Register a store Listener

  • There's another method you have access to on the Redux store object is store.subscribe(). What this does is basically subscribe a function to your store that simply logs a message every time an action is received and the store is updated.
  • FreeCodeCamp Code:
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 // 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); 
Enter fullscreen mode Exit fullscreen mode
  • Basically what they want us to do is to write a callback function that increments the global variable count every time the store receives an action, and pass this function in to the store.subscribe() method.

  • Answer:

let count = 0; store.subscribe(function() { count += 1 }) 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)