I'm trying to display the name of an image when it is uploaded to a form. So, I created a state for that. I have a function that handles image upload and another function that submits the form. So, I have to declare the formData outside the function because I want to submit both the image and form at the same time. The issue is, calling setState() re-renders and causes the uploaded image to upload again.
I already found a solution by storing the image in a state, hence it does not lose the data after re-render. I want to find out if there is any better way of doing this.
const [ImageUploaded, setImageUploaded] = useState('')
const [response, setResponse] = useState(null)
const [error, setError] = useState(null)
const [loading, setLoading] = useState(false)
let fd = new FormData()
const onImageUpload = async (e) => {
let file = e.target.files[0]
fd.append('file', file)
setImageUploaded(file.name)// this causes a re-render and fd re-initializes and data saved is lost
}
const uploadProduct = async(e) => {
e.preventDefault()
setLoading(true)
try {
const productData = {
productName: inputState.productName.value,
description: inputState.description.value,
price: inputState.price.value,
quantity: inputState.quantity.value
}
const {data} = await axios.post('/api/products/new', productData)
const response = await axios.post(`/api/upload/${data.id}`, fd, {
headers: { 'Content-Type': `multipart/form-data` },
onUploadProgress: (uploadState) => console.log(uploadState.loaded)
})
setLoading(false)
if (response.status===200) {
setResponse(true)
}
} catch (error) {
setLoading(false)
setError(true)
}
}
You can use let ImageUploaded except use this in useState case. Because when you use useState for your variables your current part re render and your previous let data may be lost.