c.casci
c.casci

Reputation: 51

Passing many props inside dispatch with Redux

With Redux, when passing state and dispatch from a component via connect, there is a need to use some state values inside dispatch when clicking a button (that is generated by map).

I bypassed a value inside my button tag with value, but it doesn't seem like the smart way to do it and it allows only one state. Any conceptual mistake here?

import React from 'react'
import { connect } from 'react-redux';
import { manageGold, addEnhancement } from '../actions/actions'

const mapStateToProps = (state) => {
    return {
        enhancements: state[0].enhancements
    }
}

const mapDispatchToProps = dispatch => {
    return {   
        manageBuyEnhancement: (event) => {
            dispatch(addEnhancement(/* Pass Enhancement Here */))   
            dispatch(manageGold(event.target.value))        
        }
    }
}

function Enhancements(props) {
    return (
        <div>
            <h4>Enhancements</h4>
            {props.enhancements.map(enh =>
                <div key={Math.random()}>
                    <p>{enh.enhancementName}</p>
                    <p>Price: {enh.enhancementPrice}</p>
                    <p>Qty: {enh.enhancementQty}</p>
                    <button onClick={props.manageBuyEnhancement} value={enh.enhancementName}>Buy!</button>
                </div>

                )
            }
        </div>
    )
}

export default connect(
    mapStateToProps, 
    mapDispatchToProps,
    null,
    {
        pure: false
    }
)(Enhancements)

Upvotes: 0

Views: 42

Answers (1)

Mateusz Krzyżanowski
Mateusz Krzyżanowski

Reputation: 582

You can add as many arguments as you want. You can use for that function or higher order function.

manageBuyEnhancement: (event, enhancement)=>{
  dispatch(addEnhancement(enhancement))   
  dispatch(manageGold(event.target.value))
}

...

<button onClick={event=>props.manageBuyEnhancement(event,enhancement)} value={enh.enhancementName}>Buy</button>

or

manageBuyEnhancement: enhancement => event =>{
  dispatch(addEnhancement(enhancement))   
  dispatch(manageGold(event.target.value))
}
...
 <button onClick={props.manageBuyEnhancement(enhancement)} value={enh.enhancementName}>Buy</button>

Upvotes: 1

Related Questions