Ad

React Axios - Losing This Context Despite Using Arrow Functions

I have in my component this function to post data. This works fine, but on the success message, the this context of my component is lost. Why? I'm using arrow functions. Why is the this context being lost this way? The problem is to call the function this.props.onUpdate(); if the post is successful.

handlePriceUpdateClickConfirm(event) {
    event.preventDefault();
    axios.post('../data/post/json/massUpdatePrices', {
        _token : window.Laravel.csrfToken,
        percent: this.refs.percent.value,
        IDs: this.props.selectedFreights,
    })
    .then((response) => {
        console.log(response);
        if(response.data != undefined && response.data != null && response.data.success == true) {
            this.props.onUpdate();
        }
    })
    .catch(function (error) {
        console.log(error);
    });
}
Ad

Answer

Because the main function, handlePriceUpdateClickConfirm, is not bound to the class itself since it is not an arrow function (nor bound, I imagine), and all functions get the same context as this one.

You could solve it by changing your function declaration to the following. I would also recommand deconstructing your props to keep your variables declared in your function's scope :

handlePriceUpdateClickConfirm = event => {
    const { onUpdate } = this.props
    /* */
    if(response.data && response.data && response.data.success) {
        onUpdate();
    }
}
Ad
source: stackoverflow.com
Ad