I'm making toy-project. And I have troubles with updating usestate... I just wanna update [images] immediately. I cannot use useEffect because this code is in try~catch... How can fix my code?
In the code, when button get clicked, the Sub function would be implemented. After posting data to the server, [images] can store data from server by setImages. The point is that, After this function finished The data in [images] should be used immediately. But it doesn't save data right away. So there happens problem. How can I set [images] right away after axios.post?
const Sub = async (e) => {
e.preventDefault()
const formData = new FormData()
formData.append("image1", file)
try {
const res = await axios.post("/images", formData, {
headers: { "Content-Type": "multipart/form-data" },
onUploadProgress: (e) => {
setPercent(Math.round(100 * e.loaded / e.total))
}
})
setImages([...images, res.data])
alert("Uploading Success!")
setTimeout(() => {
setPercent(0)
setFileName("Upload your image")
setImg(null)
}, 600);
} catch (err) {
setPercent(0)
setFileName("Upload your image")
setImg(null)
alert("Uploading Fail!")
}
}