why action.payload use in reactjs

Leya Varghese picture Leya Varghese · Apr 9, 2018 · Viewed 10.8k times · Source

action.payload is called when,where and why?? Please anyone help me to understand what is the actual use of action.payload.I already searched so many siteS, but I doesn't get it..

Answer

anulal sreeranjanan picture anulal sreeranjanan · Apr 9, 2018

When you are handling a request, say onclick of an element we need to update the state

In that case we will use like this

<div onClick={this.props.handleClick()} >

this handleClick will be described in the actions, where we will create an action creator. Each action creator contains an action and payload which contains the data we need to pass to the reducers.

A sample action creator will look like the following

const data = 'sample data here'

return {
  type: 'SELECT_ACCOUNT',
  payload: data
}

On the reducers inside the switch case we will handle the action type and update the app mapStateToProps Example shown below

case SELECT_ACCOUNT:
  return {
    ...state,
    selected : action.payload
 };

Hope this will help you to get a basic idea