Search code examples
javascriptreactjsreduxreact-reduxredux-toolkit

Payload in Redux Toolkit


Can someone explain to me what is payload in redux-toolkit?

Where does this value come from?

import { createSlice, PayloadAction } from '@reduxjs/toolkit'

export interface CounterState {
  value: number
}

const initialState: CounterState = {
  value: 0,
}

export const counterSlice = createSlice({
  name: 'counter',
  initialState,
  reducers: {
    increment: (state) => {
      state.value += 1
    },
    decrement: (state) => {
      state.value -= 1
    },
    incrementByAmount: (state, action: PayloadAction<number>) => {
      state.value += action.payload
    },
  },
})


export const { increment, decrement, incrementByAmount } = counterSlice.actions


export default counterSlice.reducer

Solution

  • The action.payload created by createAction function. These three fields (payload, meta and error) adhere to the specification of Flux Standard Actions.

    Payload:

    The optional payload property MAY be any type of value. It represents the payload of the action. Any information about the action that is not the type or status of the action should be part of the payload field. By convention, if error is true, the payload SHOULD be an error object. This is akin to rejecting a promise with an error object.