'React state not updating after a post request?
I'm trying to send a post request to my backend with axios, and my backend gets the values with no problem, but I want to set a state of (sent) to true when the post request is "successfully sent", I put the setSent(true)
in the .then()
after the axios request. but when I send the request the state isn't updated! what could be the problem? backend gets the values and works fine though... see code bellow:
const submitHandler = () => {
axios
.post(
"/sendFeedback",
qs.stringify({
name,
email,
text,
})
)
.then(() => {
setSent(true) // doesn't work (the state is still false)
})
.catch((err) => {
err && setError(true) // works just fine!
})
}
Solution 1:[1]
try
const submitHandler = async () => await axios ...
because it's asynchronous process and returns a promise.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | GraÅžvydas Untulis |