Search code examples
javascriptreactjsreduxactionreact-props

Passing a prop into an action creator in Redux


I am trying to pass the ID number (as a prop) into my action creator function on an onClick event. I have used this syntax before when using setState() but it doesn't seem to be working here. I am new to redux and am not finding an answer in the docs. I have console.logged to confirm that all the necessary props are being passed appropriately.

When I console.log(action.payload) in my reducer function, it returns as undefined. If you would like me to post more code, I can.

I am concerned with addCard

const mapDispatchToProps = dispatch => ({
  addMarket: () => dispatch(actions.addMarket()),
  addCard: () => dispatch(actions.addCard())
});

Component which has the onClick

const MarketDisplay = (props) => (
  <div className="marketBox">
    <h3>{props.totalMarkets}</h3>
    <h3>Market ID:</h3> <p>Market</p>
    <h3>Location:</h3> <p>Location</p>
    <h3>Cards:</h3> <p>Cards</p>
    <h3>% of total:</h3> <p>% of total</p>
    <button onClick={() => props.addCard(props.id)}>Add Card</button>
  </div>
);

action object

import * as types from '../constants/actionTypes'

export const addCard = (marketId) => ({
  type: types.ADD_CARD,
  payload: marketId,
}
);

Solution

  • You should forward (or proxy) the id to the action creator

    const mapDispatchToProps = dispatch => ({
      addMarket: () => dispatch(actions.addMarket()),
      addCard: (id) => dispatch(actions.addCard(id)) // <-- pass id to action creator
    });
    

    UI, now passing props.id will work.

    onClick={() => props.addCard(props.id)}
    

    Fun Fact: You Might Not Need The mapDispatchToProps Function

    The redux connect HOC will automagically wrap actions in mapDispatchToProps in a call to dispatch, so you can write a mapDispatchToProps that looks like this

    const mapDispatchToProps = {
      addMarket: actions.addMarket,
      addCard: actions.addCard
    };
    

    And since the function signature of addCard already takes an id

    export const addCard = (marketId) => ({
      type: types.ADD_CARD,
      payload: marketId,
    });
    

    then your onClick code will still work as expected.