Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

105
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda