Blog>
Snippets

Using Constants for Action Types

Provide an example of defining action types with constants to maintain consistency and adhere to the string type requirement in Redux v5.0.0.
// action-types.js
export const ADD_TODO = 'ADD_TODO';
export const REMOVE_TODO = 'REMOVE_TODO';
Defines constants for the action types to be used in the application. This ensures that the action types are strings as required by Redux v5.0.0 and helps maintain consistency throughout the application.
// actions.js
import { ADD_TODO, REMOVE_TODO } from './action-types';

export function addTodo(text) {
  return {
    type: ADD_TODO,
    payload: text
  };
}

export function removeTodo(id) {
  return {
    type: REMOVE_TODO,
    payload: id
  };
}
Creates action creator functions that use the defined action type constants. This demonstrates how to properly dispatch actions using the constants, thereby ensuring consistency and compliance with Redux's string type requirement.
// reducer.js
import { ADD_TODO, REMOVE_TODO } from './action-types';

function todoReducer(state = [], action) {
  switch (action.type) {
    case ADD_TODO:
      return [...state, action.payload];
    case REMOVE_TODO:
      return state.filter(todo => todo.id !== action.payload);
    default:
      return state;
  }
}
Utilizes the constants in the reducer to match action types when updating the state. This helps avoid errors and improve maintainability by ensuring that the reducer and action creators use the same values for action types.