[solved] Understanding Redux actions managed by the reducer function

HI!

I’d like some help understanding how the reducer function reads the action functions. I can’t understand that by reading the code. In other words (from “Redux: Handle an Action in the Store” ), how does the reduce function below understand that “action” refers to loginAction action creator. I can’t read that from the code.

Spoiler
const defaultState = {
  login: false
};

const reducer = (state = defaultState, action) => {
  // change code below this line
if (action.type === 'LOGIN') {
    return  {
    login: true
    } 
    } else {
      return state
  // change code above this line
};

const store = Redux.createStore(reducer);

const loginAction = () => {
  return {
    type: 'LOGIN'
  }
};

Actions in redux are dispatched to reducers. Actions have a type property with certain string.

When the reducer receives these dispatched actions, it reads them through the 2nd parameter, in this case action. Inside the function, you compare the string and update the state from the reducer.

1 Like

Reduce function doesn’t know about loginAction nor does it care.

loginAction is called action creator and is just a convenience so you don’t have to deal with objects.

The code is missing dispatch part. That’s what connects your action (or action creator) to reducer. When you call store.dispatch(myActionCreator) it gets dispatched to all reducers which were used in createStore (in your case there is only one reducer). Then every reducer will look into action argument for the type field and will go through it’s if/switch statements trying to find matching statement. If nothing is found the else/default case is executed (usually just return state unchanged`).

So in short data flow is like this:

store.dispatch(loginAction) ==> reducer ==> if statement ==> state updated
1 Like

Exactly, now it makes sense. The dispatch part missing breaks the understanding completely. Just went checking the FCC solution and it also misses the dispatch part https://guide.freecodecamp.org/certifications/front-end-libraries/redux/handle-an-action-in-the-store/

Thanks a lot @jenovs and @shimphillip