Reputation: 3
my friends I'm making a react class that gets an input value when the form is submitted, to send a get request using axios
but i got result after the second click
class SearchForm extends React.Component{
constructor(props) {
super(props);
this.state = {inputtermvalue: "",spaces_list: "",spacesname: ""};
}
componentDidMount() {
}
updateInputValue(evt){
this.setState({inputtermvalue: evt.target.value});
}
handleSubmit(){
this.setState({spaces_list: $("input.sp-autocomplete-spaces").val()});
this.sendGetRequest();
}
sendGetRequest(){
var _this = this;
this.serverRequest =
axios
.get("/rest/1.0/term/search", {
params: {
query: this.state.inputtermvalue,
spaces: this.state.spaces_list
},
headers: {'content-type': 'application/json'}
})
.then(({data}) => {
Upvotes: 0
Views: 438
Reputation: 16441
setState
is an asynchronous call, so you can't expect it to immediately finish before continuing. In your code here:
handleSubmit(){
this.setState({spaces_list: $("input.sp-autocomplete-spaces").val()});
this.sendGetRequest();
}
You are updating state and then calling a method that uses that new state value. What could be happening is that you are calling this.sendGetRequest
before your state has finished updating.
You should use the componentDidUpdate
lifecycle hook to make sure that state is finished updating before calling this.sendGetRequest
:
handleSubmit () {
this.setState({
spaces_list: $("input.sp-autocomplete-spaces").val()
});
}
componentDidUpdate (prevProps, prevState) {
if(prevState.spaces_list !== this.state.spaces_list) {
this.sendGetRequest();
}
}
Upvotes: 1