Tom Pinchen
Tom Pinchen

Reputation: 2497

Passing state into an Ajax call ReactJS and Rails

I have a ProductItem component that when the user clicks 'Add to Basket' performs an AJAX post call to create a basket item.

However I can't seem to pass state into the Ajax call at the moment and so it's missing the dynamic data it needs.

The component looks like this and state is setting correctly on the Product Item component when I check in react developer tools on chrome.

class ProductItem extends React.Component{

constructor() {
    super()

    this.state = { 
        name: '',
        price: 0,
        code: '',
        id: ''
    }
}

componentWillMount() {
    this.setState( {
        name: this.props.data.name,
        price: this.props.data.price,
        code: this.props.data.code,
        id: this.props.data.id
    })
}

addtoBasket(props) {
    console.log(props.name) /* RETURNS UNDEFINED */
    $.ajax({
        type: "POST",
        url: "/items",
        dataType: "json",
        data: {
            item: {
                name: 'Trousers',
                price: 52.00,
                code: 'T01'
            }
        },
        success: function() {

            console.log("success");
        },
        error: function () {
            console.log("error");
        }
    })
}

render(){
    let productName = this.props.data.name
    let productPrice = this.props.data.price
    let productCode = this.props.data.code
    let productImg = this.props.data.image_url

    return (
        <div className="col-xs-12 col-sm-4 product">
            <img src={productImg}/>
            <h3 className="text-center">{productName}</h3>
            <h5 className="text-center">£{productPrice}</h5>
            <div className="text-center">
                <button onClick={this.addtoBasket.bind(this.props)} className="btn btn-primary">Add to Basket</button>
            </div>
        </div>
    )
}

}

How can I fix this and correctly pass state or props to the call?

Upvotes: 2

Views: 678

Answers (2)

Amit
Amit

Reputation: 3289

Change your button to below code

<button onClick={this.addtoBasket.bind(this)} className="btn btn-primary">Add to Basket</button>

And then you will be able to get the context of this.

Or other way

 <button onClick={this.addtoBasket.bind(this , this.props)} className="btn btn-primary">Add to Basket</button>

And in addtoBasket method

addtoBasket(props){
  console.log("Prrops" , props)
}

That should work :)

Upvotes: 1

Michal Př&#237;hoda
Michal Př&#237;hoda

Reputation: 291

The problem is in this.addtoBasket.bind(this.props) call - the bind method's argument will become this in the bound function. So called like this it binds props to be this, not the class.

You probably wanted to do this.addtoBasket.bind(this) instead.

And the addtoBasket function's argument will be the onClick event, not the props.

Upvotes: 1

Related Questions