Just can't think of a way to do this: I have a form and make an ajax request with the input upon submission, but how do I ensure that the state is completely set before I make the request? I know that setState is asynchronous and a version that accepts a callback exists, but I don't want to submit as soon as the state is set, rather when the user clicks the submit button. When I make the request, this.state is null still.
Any help or tips would be appreciated, thank you!
import React from 'react';
export default class Landing extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
this.handleChange = this.handleChange.bind(this);
this.state = {
question: ""
};
}
handleClick(e) {
const xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState === XMLHttpRequest.DONE) {
if (xhttp.status === 200) {
console.log("success")
} else {
alert('There was a problem with the request.');
}
}
};
xhttp.open('POST', '/save', true);
xhttp.setRequestHeader("Content-Type", "application/json");
xhttp.send(JSON.stringify({ question: this.state.question }));
}
handleChange(e) {
this.setState({ question: e.target.value });
}
render() {
return (
<div className="landing">
<form onSubmit={this.handleClick}>
<label>
Question:
<input type="text" value={this.state.question} onChange={this.handleChange} />
</label>
<input type="submit" value="Submit" />
</form>
</div>
);
}
}