Reputation:
I am trying to send post request using axios in Reactjs.
I have two component a timer
component and App
component and in App component i am trying to submit a form and send an axios call when i fetch the time from Timer component and save itinto counter
state
I have written a condition if counter is true then update my state and then further send the post request
Working Demo here is a handle submit code:
const handleSubmit = e => {
console.log("handleSubmit");
e.preventDefault();
if (counter) {
console.log(counter);
const url = `url string`;
setState({
...state,
lastn: {
attestedTime: myDateFunc(),
time: counter
}
});
console.log(state);
axios
.post(url, state)
.then(response => {
console.log(response);
console.log(response.data);
})
.catch(error => {
console.log(error);
});
}
};
The problem is when counter is true its not update the state which causes error while send axios request.
I have consoled each and every thing but still it fails. It seems there is lot of rendering.
Upvotes: 0
Views: 1152
Reputation: 3207
If you are using class components, you can make the reuqest after the state has been set. Something like this:
this.setState({
...state,
lastn: {
attestedTime: myDateFunc(),
time: counter
}
}, () => {
axios
.post(url, state)
.then(response => {
console.log(response);
console.log(response.data);
})
.catch(error => {
console.log(error);
});
});
Since you did set the react-hooks
tag, I guess that approach is not what you need. In your case, I suggest saving new state in some temporary variable and than passing that variable to axios
. Like this:
const newState = {
...state,
lastn: {
attestedTime: myDateFunc(),
time: counter
}
};
setState(newState);
axios
.post(url, newState)
.then(response => {
console.log(response);
console.log(response.data);
})
.catch(error => {
console.log(error);
});
Upvotes: 2
Reputation: 36
setState
can be executed asynchronously by React, to optimize the rendering process. For cases like this one, it can also take a callback function that is guaranteed to be executed after updating the state.
For example:
this.setState({
name:'value'
},() => {
console.log(this.state.name);
});
in this case console.log
will be executed after setting the name
variable.
see the docs: https://reactjs.org/docs/react-component.html#setstate
Upvotes: 0