Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass parameters to mapDispatchToProps()

I can't lie, i'm a bit confused about react-redux. I think lot of the actions require parameters (for an example deleting items from the store), but even if i'm still reading about how to dispatch from component in that way to pass a parameter, about 2 hours now, i didn't get any answers. I was tried with this.props.dispatch and with mapDispatchToProps, i always get the this.props... is not a function message. Here's what i'm trying to do:

  const getTheArray = (array) => {
    return {
      type: 'GET_ARRAY',
      array
    }
  }
    
    class Example extends......
    
    componentDidUpdate(){
    //i have a button, and when it clicked, turns the status: 'deleted'
        if (this.state.status === 'deleted'){
            fetch('http://localhost:3001/deleteitem', {
                method: 'post',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({
                    id: this.props.id
                })
            })
            .then(res => res.json())
            .then(data => this.props.deleteFromArray(data))
            .catch(err => console.log(err)) 
        }
    }




function mapStateToProps(state) {
    return {
        array: state.array
    };
}
function mapDispatchToProps(dispatch) {
    return({
        deleteFromArray: (array) => {dispatch(getTheArray(array))}
    })
}
  
export default connect(mapStateToProps, mapDispatchToProps)(Example);

It isn't the only place where i need to dispatch with an action, where the action's object's properties depending on another property passed to the function, so i really want to do, what's the best way to pass property to action, and dispatch it within a react component.

like image 960
Gergő Horváth Avatar asked Jun 03 '18 17:06

Gergő Horváth


1 Answers

import { bindActionCreators } from "redux"

function mapDispatchToProps(dispatch) {
    return(bindActionCreators({
        deleteFromArray: (array) => {getTheArray(array)}
    }, dispatch))
}

In your dumbComponents, just call e.g this.props.deleteFromArray([1,2,3,4])

This should solve the issue. you are not binding with dispatch

like image 157
simbathesailor Avatar answered Sep 27 '22 21:09

simbathesailor