bier hier bier hier - 1 month ago 8
React JSX Question

How can I trigger a dispatch?

I am having trouble triggering a dispatch in my redux app. This is my container/ part of it:

render() {
debugger;
var Packs = [];
if (this.props.packsData != undefined && this.props.packsData.existingFoxtelPackage != undefined) {
if (this.props.packsData.existingFoxtelPackage.eligiblePacks.length > 0) {

Packs = this.props.packsData.existingFoxtelPackage.eligiblePacks;

console.log('testing=Packs', Packs);
}
}

return (
<div>hello from Packscontainer!!!
<div>
{
Packs.map(pack =>
<Pack id={pack.id} name={pack.name} addToCart={() => store.dispatch({type:'ADD_TO_CART',id:pack.id})}/>
)}
</div>
</div>
)
}


The child Pack component looks partially this:

render() {
const { addToCart } = this.props
return (
<div>hello from pack
{this.props.id} - {this.props.name}

<button onClick={addToCart}>Add to cart</button>
</div>
)
}


This is the reducer:

const initialState = {
cartIds: []
}

const Cart = (state = initialState.cartIds, action) => {
switch (action.type) {
case 'ADD_TO_CART':
debugger;
return [...state, action.id]
default:
return state
}
}

export default Cart;


How can I trigger the dispatch with the addToCart?

Answer

If you use redux in a correct way , the dispatch would be injected into your container as a prop. So the code in your container should be like this:

render() {
    debugger;
    var Packs = [];
    if (this.props.packsData != undefined  && this.props.packsData.existingFoxtelPackage != undefined) {
        if (this.props.packsData.existingFoxtelPackage.eligiblePacks.length > 0) {

            Packs = this.props.packsData.existingFoxtelPackage.eligiblePacks;

            console.log('testing=Packs', Packs);
        }
    }

    return (
        <div>hello from Packscontainer!!!
            <div>
                {
                    Packs.map(pack =>
                        <Pack id={pack.id} name={pack.name} addToCart={this.onAddToCart.bind(this, pack.id)}/>
                    )}
            </div>
        </div>
    )
}

onAddToCart(id)
    this.props.dispatch({type:'ADD_TO_CART',id:id});
}