I have just started with learning reactjs and trying to retrieve data through an ajax call. The component looks like this:
import React from 'react';
import ReactDOM from 'react-dom';
import $ from 'jquery';
class App extends React.Component {
// myTitle='';
constructor() {
super();
this.state = {val: 0};
this.update = this.update.bind(this);
}
update() {
var root = 'http://jsonplaceholder.typicode.com';
$.ajax({
url: root + '/posts/1',
method: 'GET'
}).then(function (data) {
this.state.val = data.title;
});
console.log(this.state);
}
componentWillMount() {
console.log('mounting')
}
render() {
console.log('rendering!')
return <button onClick={this.update}>{this.state.val}</button>
}
componentDidMount() {
console.log('mounted')
}
componentWillUnmount() {
console.log('bye!')
}
}
When the ajaxcall comes back it returns an error where the state.val statement is:
jQuery.Deferred exception: Cannot set property 'val' of undefined TypeError: Cannot set property 'val' of undefined
at Object.<anonymous> (http://localhost:3000/08-lifecycle-mounting/index.js:28958:33)
at mightThrow (http://localhost:3000/08-lifecycle-mounting/index.js:32563:30)
at process (http://localhost:3000/08-lifecycle-mounting/index.js:32631:13)
How can I update the state and use the returning data from the ajax call?