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
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
Ad