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..
The second one is “payload”, Payload stores the additional information about what happened. It is not a compulsion to include “payload” in the object. It is entirely up to you but we should always try to pass only the necessary information to the action object and try to keep it as light as possible.
Reducers, as the name suggests, take in two things: previous state and an action. Then they reduce it (read it return) to one entity: the new updated instance of state. So reducers are basically pure JS functions which take in the previous state and an action and return the newly updated state.
While action types allow you tell your reducer what action it should take, the payload is the data that your reducer will use to update the state.
Actions are the only source of information for the store as per Redux official documentation. It carries a payload of information from your application to store. const ITEMS_REQUEST = 'ITEMS_REQUEST'; Apart from this type attribute, the structure of an action object is totally up to the developer.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With