Redux - Register a Store Listener

Tell us what’s happening:
So, I did the exercise and passed it but I m baffled by how does the function cb find out if the condition is of ADD coz we just made it as a callback and did nothing else? I m trying to visualize it but it is hard.

Your code so far

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
const cb = ()=>{
  if(ADD){
  count = count +=1
  }
}
store.subscribe(cb)
// 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);

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36

Challenge: Redux - Register a Store Listener

Link to the challenge:

It doesn’t. The if(ADD){ is unnecessary. All that does it check if ADD (in the global scope) is truthy. Since it is defined as a non-empty string, it will always be truthy. That code will run every time the store updates. You have it checking something that will always be true, so the check is unnecessary.

Does that makes sense? Try it without that check.

I think I do but not sure how it works now that I have no check in there.is that the purpose of the the exercise

Right. It is just showing you that something is happening. You can subscribe to the store and have your callback do something every time the store is changed.

To be honest, I have never done this. This is barebones redux - I always use it in the context of React where you access it a little differently. It’s still good to learn, but don’t freak out if it doesn’t make perfect sense. I didn’t do the FCC redux stuff (it didn’t exist when I was learning) but when I was learning I remember being very confused about what was happening. Even after I was using it, in a real job, it was probably six months before it finally clicked what was really happening. It’s a different way of thinking - it just takes time.

1 Like

If you want more information the docs are your best bet.