DEV Community

Randy Rivera
Randy Rivera

Posted on • Updated on

Redux: Use a Switch Statement to Handle Multiple Actions

  • With Redux store you can tell it how to handle multiple action types. Like FreeCodeCamp is providing for us, let's say we're managing user authentication in our Redux store. You want to have a state representation for when users are logged in and when they are logged out. You represent this with a single state object with the property authenticated. You also need action creators that create actions corresponding to user login and user logout, along with the action objects themselves.
  • Code:
const defaultState = {
  authenticated: false
};

const authReducer = (state = defaultState, action) => {
  // Change code below this line

  // Change code above this line
};

const store = Redux.createStore(authReducer);

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

const logoutUser = () => {
  return {
    type: 'LOGOUT'
  }
};
Enter fullscreen mode Exit fullscreen mode
  • Here we have a store, actions, and action creators set up for us. We just have to fill in the reducer function to handle multiple authentication actions. We need to use JavaScript switch statement in the reducer to respond to different action events. The switch statement should switch over action.type and return the appropriate authentication state. Also, don't forget to write a default case in your switch statement that returns the current state.
  • Answer:
const authReducer = (state = defaultState, action) => {
  switch(action.type) {
    case 'LOGIN':
    return {authenticated: true}
    case 'LOGOUT':
    return {authenticated: false}
    default:
    return defaultState
  }

};

const store = Redux.createStore(authReducer);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)