DEV Community

Randy Rivera
Randy Rivera

Posted on

Redux: Use const for Action Types

  • Welcome again and thank you for continuing this journey with me. Today FreeCodeCamp wants us to work with action types. When working with Redux its common practice to assign action types as read-only constants( const declarations), then reference these constants wherever they are used.
  • Code:


const defaultState = {
  authenticated: false
};

const authReducer = (state = defaultState, action) => {

  switch (action.type) {
    case 'LOGIN': 
      return {
        authenticated: true
      }
    case 'LOGOUT': 
      return {
        authenticated: false
      }

    default:
      return state;

  }

};

const store = Redux.createStore(authReducer);

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

const logoutUser = () => {
  return {
    type: 'LOGOUT'
  }
};
Enter fullscreen mode Exit fullscreen mode
  • FreeCodeCamp wants us to declare LOGIN and LOGOUT as const values and assign them to the strings 'LOGIN' and 'LOGOUT', respectively. Then, edit the authReducer() and the action creators to reference these constants. Remember to write them all uppercase.

  • Answer:

const LOGIN = 'LOGIN'
const LOGOUT = 'LOGOUT'

const defaultState = {
  authenticated: false
};

const authReducer = (state = defaultState, action) => {

  switch (action.type) {
    case LOGIN: 
      return {
        authenticated: true
      }
    case LOGOUT: 
      return {
        authenticated: false
      }

    default:
      return state;

  }

};

const store = Redux.createStore(authReducer);

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

const logoutUser = () => {
  return {
    type: LOGOUT
  }
};
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
markerikson profile image
Mark Erikson

FWIW, FCC's Redux course is unfortunately outdated (as are many other tutorials online).

It'll help teach you the basics, but "modern Redux" with Redux Toolkit is a lot simpler and easier to learn. In fact, with Redux Toolkit you don't have to write any action types or action creators yourself. RTK's createSlice API generates those for you automatically behind the scenes.

See our official Redux docs tutorials:

redux.js.org/tutorials/index