Handling State (Action Payloads & Action Creators)

Action Payloads & Action Creators

  • payload - A payload is a property of an action object that carries any data necessary for the action to be processed by a reducer().

  • action creator - action creator is a function that creates and returns an action object. Using action creators can make your code more modular.

Redux Counter Application

Simple Redux app with action and payload

// Get DOM elements for counter, increment, and decrement buttons
const counterElement = document.getElementById("counter");
const incrementElement = document.getElementById("increment");
const decrementElement = document.getElementById("decrement");

// Action identifiers
const INCREMENT = "increment";
const DECREMENT = "decrement";

// Action Creators
const increment = (value) => {
  return {
    type: INCREMENT,
    payload: value,
  };
};

const decrement = (value) => {
  return {
    type: DECREMENT,
    payload: value,
  };
};

// Define initial state for the counter
const initialState = {
  value: 0,
};

// Define a reducer function for the counter that handles actions
const counterReducer = (state = initialState, action) => {
  // If the action is "increment", return a new state with the value incremented by 1
  if (action.type === INCREMENT) {
    return {
      ...state, // Copy the existing state
      value: state.value + action.payload, // Update the value property
    };
  }
  // If the action is "decrement", return a new state with the value decremented by 1
  else if (action.type === DECREMENT) {
    return {
      ...state, // Copy the existing state
      value: state.value - action.payload, // Update the value property
    };
  }
  // If the action is not recognized, return the existing state
  else {
    return state;
  }
};

// Create a Redux store with the counter reducer
const store = Redux.createStore(counterReducer);
console.log(store); // Log the store to the console for debugging purposes

// Define a render function that updates the counter element with the current state
function render() {
  const state = store.getState(); // Get the current state from the store
  counterElement.innerText = state.value.toString(); // Update the counter element with the current value
}

render(); // Call the render function to update the counter element with the initial state

// Subscribe the render function to the store, so that it is called whenever the state changes
store.subscribe(render);

// Add event listeners to the increment and decrement buttons
incrementElement.addEventListener("click", () => {
  // Dispatch an "increment" action to the store
  store.dispatch(increment(3));
});

decrementElement.addEventListener("click", () => {
  // Dispatch a "decrement" action to the store
  store.dispatch(decrement(2));
});

Last updated

Was this helpful?