map state to props or the one after that.
what is happening, please help
this one and challenge before this one
what is happening, please help
When you write the function mapDispatchToProps
react-redux ( which is a package used behind the scenes) detect the use of this function and pass it the dispatch function as an argument.
He do that because
[dispatch(action)] This is the only way to trigger a state change
from Store | Redux
Doing so mapDispatchToProps maps through the props of the object returned from your function and use dispatch(prop)
on each of them, allowing you to bind all those props to actions triggered against the store.
It doesn’t make much sense but if your mapDispatchToProps
function returns an object like this :
{
a: 1,
b: 2
}
what it would happen will be :
- a: dispatch(1)
- b: dispatch(2)
which has no effect and throws a bunch of error i guess, but i think it can help to visualize what’s happening here ^^
I know this could be not so clear, it will become with the time. Meanwhile below you find the breakdown of the challenge ( unfortunately i had to spoiler it, coudn’t refactor with a similar example ):
Write the function mapDispatchToProps()
|| that takes dispatch
as an argument, then returns an object. || The object should have a property submitNewMessage
|| set to the dispatch function, || which takes a parameter for the new message || to add when it dispatches addMessage()
.
- Write the function mapDispatchToProps()
function mapDispatchToProps() {};
- that takes dispatch as an argument, then returns an object.
function mapDispatchToProps(dispatch) {
return {};
};
- The object should have a property submitNewMessage
function mapDispatchToProps(dispatch) {
return {
submitNewMessage: ''
};
};
- set to the dispatch function, ( this could be much clear )
function mapDispatchToProps(dispatch) {
return {
submitNewMessage: function() {
dispatch()
}
};
};
- which takes a parameter for the new message
function mapDispatchToProps(dispatch) {
return {
submitNewMessage: function(message) {
dispatch()
}
};
};
- to add when it dispatches addMessage().
function mapDispatchToProps(dispatch) {
return {
submitNewMessage: function(message) {
dispatch(addMessage(message))
}
};
};