Friday, August 14, 2020

Actions in Redux

An Action is a plain JavaScript object which has a Type property which defined the type of the actions and an optional payload. Actions are triggers which are used to send information from the application to the store and these are the only way in which the redux store can be modified.

Below is an example of a simple action object.
  return {
      type: SET_NAME,
      payload: {value}
    };

The type: SET_NAME is the type of action and the payload: {} can contain an object which will be passed from the application to the store, the data is the payload object can be used to update the store object.

Actions are triggered using store.dispatch()

Action Creators
Action creators are wrapper functions which return an action object, these functions are called from the React application to dispatch the action. Below is an example of a simple action creator function.

export function SetName(value) {
  return {
      type: SET_NAME,
      payload: {value}
    };
}

Action creators are triggered by mapDispatchToProps in the React application. In the below sample the setName() method will call the SetName action creator with a parameter value. This, in turn, will dispatch the SET_NAME action with payload: {value}

const mapDispatchToProps = dispatch => {
  return {
    setName: (value) => { dispatch(SetName(value)) },
    setGreeting: (name) => { dispatch(SetGreeting(name)) }
  }
};

The setName() function can be called from anywhere in the React Component which will trigger the action, the reducer will modify the state.


Search Flipkart Products:
Flipkart.com

No comments: