Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is difference between dispatch and bindActionCreators?

Tags:

If we are connecting to the action by using the dispatch there are two way:-

1. this.props.dispatch(requestEmployees());  2. const mapDispatchToProps = (dispatch) => ({       requestEmployees: () => dispatch(requestEmployees())      }); 

If we are doing the same with the help of bindActionCreators then our code we will be:-

function matchDispatchToProps(dispatch) {         return bindActionCreators({ editLabResult: requestEmployees}, dispatch);     } 

Now my question is, which one I should use dispatch or bindActionCreators? What is the difference between them?

like image 961
Gorakh Nath Avatar asked Dec 27 '16 09:12

Gorakh Nath


People also ask

What is the use of bindActionCreators?

bindActionCreators(actionCreators, dispatch) Turns an object whose values are action creators, into an object with the same keys, but with every action creator wrapped into a dispatch call so they may be invoked directly. Normally you should just call dispatch directly on your Store instance.

What are the two parameters of bindActionCreators?

bindActionCreators accepts two parameters: A function (an action creator) or an object (each field an action creator) dispatch.

When mapDispatchToProps is called?

So every time your state is changed mapStateToProps will be called with your new state and subsequently as you props update component will run render function to render your component in browser. mapDispatchToProps also stores key-values on the props of your component, usually they take a form of a function.


1 Answers

It's actually the same thing. The result of

bindActionCreators({ editLabResult: requestEmployees}, dispatch); 

Is what you've manually created:

requestEmployees: () => dispatch(requestEmployees()) 

According to the redux bindActionCreators documentation:

Turns an object whose values are action creators, into an object with the same keys, but with every action creator wrapped into a dispatch call so they may be invoked directly.

bindActionCreators({ editLabResult: requestEmployees, anotherAction, etc... }, dispatch); 

Instead of using bindActionCreators, you can pass the object to the connect method, and it will do the wrapping for you:

connect(mapStateToProps, { editLabResult: requestEmployees, anotherAction, etc... }) 
like image 192
Ori Drori Avatar answered Oct 06 '22 20:10

Ori Drori