Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

110
Views
I keep losing my values stored in a let, each time I call set State

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)
    } 
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!