[Done] React and Redux: Map Dispatch to Props

I can’t seem to understand the instructions properly.

My first instinct was

const mapDispatchToProps = (dispatch) => {
    return {
        submitNewMessage: dispatch(addMessage(newMessage))
    }
};

But I get the error “newMessage is not define”

So I tried:

const mapDispatchToProps = (dispatch) => {
    return {
        submitNewMessage: dispatch(addMessage)
    }
};

which got the error “dispatch is not a function”

I’m struggling to figure out how to pass in newMessage when it’s not indicated as a parameter for the overall function…

What am I missing?

1 Like

Hint: The instructions are not explicit on this, but the example shows what the test expects

submitLoginUser: function(username) {
    dispatch(loginUser(username));
  }

And you had this

submitNewMessage: dispatch(addMessage(newMessage))

By fixing that you will also have access to your named newMessage argument.

2 Likes

Thanks JM, that did it! I feel dumb, should have been able to figure that out on my own.

Follow-up question:
Is there a reason you used that notation instead of ES6? Using your example, I converted it to the following and it worked:
submitNewMessage: ( username => { dispatch(loginUser(username)) } )

But is there a best-practice reason to use the function(arg){…} format?

No best practice, just per project standards. I only copied pasted the FCC example. I usually stick to straight es6 like this

const mapDispatchToProps = dispatch => ({
   submitNewMessage: username => dispatch(loginUser(username))
})

If you only knew the silly mistakes I spent days troubleshooting in my code, you wouldn’t feel so dumb. lol :slight_smile:

2 Likes

Ok cool, I just wanted to check. Thank you for your help, I really appreciate it!

1 Like

const mapDispatchToProps=(dispatch)=>{
return {
submitNewMessage: function(message) {
dispatch(addMessage(message));
}
}
};

this works form me.!

3 Likes

Thanks! you can skip the first parenthesis set, by the way!

For those who came after me

// change code below this line
/*

  1. “mapDispatchToProps” is passed a function aka “x” as an argument
  2. We return an object with key “submitNewMessage”
  3. This key will be a function with parameter “y”
  4. it calls “x” with addMessage(y) where “y” is passed as an arguments
    */

const mapDispatchToProps = x => ({
submitNewMessage: y => x(addMessage(y))
});

It took alil time and some research with some cheating :stuck_out_tongue_winking_eye:, but I got it DONE

const addMessage = (message) => {
  return {
    type: 'ADD',
    message: message
  }
};

// change code below this line
const mapDispatchToProps = (dispatch) => {
     return {
        submitNewMessage: function(username) {
             dispatch(addMessage(username));
        }
  }
    
};
1 Like

Thank for this one. It was helpful.