Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

104
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda