I've found other posts with the similar errors, but those had functions which needed to be binded.
In the simple program below where I'm trying to update the DOM after an AJAX request is successful, I get the error ".TypeError: this.setState is not a function". Please help me understand why this code is not working.
import React from 'react';
import logo from './logo.svg';
import './App.css';
export class App extends React.Component {
constructor(props) {
super(props);
this.state = {
name: '(name will be inserted after ajax request)'
};
console.log('constructor');
}
componentDidMount() {
//AJAX REQUEST
const url = 'http://localhost:8080/ping';
const xhr = new XMLHttpRequest();
xhr.responseType = 'text';
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE) {
console.log(xhr.responseText);
this.setState({name: xhr.responseText});
}
}
xhr.open("GET", url);
xhr.send();
}
render() {
console.log('render')
return <h1 > Hello {this.state.name} </h1>;
}
}