Friday, August 14, 2020

mapDispatchToProps in Redux

mapDispatchToProps function is used to dispatch actions to the store in a react-redux application.
To dispatch an action to the store we need to call store.dispatch. In a React Redux application the React component does not have access to the store directly hence it cannot call store.dispatch. The connect method which connects react and redux provides the mapDispatchToProps through which react components can dispatch actions.

If mapDispatchToProps is not defined in connect, there is another way to dispatch actions from React components. In this case props.dispatch is passed to the component and using this we can dispatch actions to the store.


function HomeComponent({ name, dispatch }) {
  return (
    <div>
      <button onClick={() => dispatch({ type: 'SET_GREETING' })}>Click</button>
    </div>
  )
}

With a mapDispatchToProps function we can specify actions to be dispatched by the component. It lets us define action dispatching functions as props. From the component, we will call these functions instead of calling props.dispatch directly.

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

mapDispatchToProps Is the second parameter to the connect which connects react and redux.

export default HomeReduxContainer = connect(mapStateToProps, mapDispatchToProps)(HomeRedux);


Search Flipkart Products:
Flipkart.com

No comments: