'update my state then send a post request with updated data
I have two requests that I need to send one after the other, the first one sends my attachments to an S3 BUCKET and the second gets the returned urls of the attachments, updates my data and send it in a post request. The problem is the send request is firing before the data is updated since useState is async. My question is how do I make sure that I await the update then send the post request. Here are my functions .
sending files function
const sendFiles=async()=>{
const config= {
headers:{
'Accept': '*/*',
}
}
for (let i = 0; i < files.length; i++) {
fileData.append("files",files[i],files[i].name)
}
for (let i=0;i<images.length;i++){
fileData.append('images',images[i],images[i].name)
}
try{
setSending(true)
const attachements=await axios.post('url',fileData,config)
setData({...data,attachements:attachements.data.files,images:attachements.data.images})
}
catch(error){
console.log(error)
setSending(false)
setFailure(true)
setTimeout(() => {
setFailure(false)
}, 2000);
}
}
Send data function
const sendData=async()=>{
console.log(data)
try{
const json =JSON.stringify(data)
const result=await axios.post("url",json)
console.log(result)
setSending(false)
setSuccess(true)
setTimeout(() => {
setSuccess(false)
}, 2000);
}
catch(error){
console.log(error)
setSending(false)
setFailure(true)
setTimeout(() => {
setFailure(false)
}, 2000);
}
}
Form submit handler function
const submitHandler=async(e)=>{
e.preventDefault()
await sendFiles()
sendData()
}
Thanks to those willing to help.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
