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

187
Visualizações
React, state setter not updating the value

useState() can't set file object. I added comments in the code to explain what's happening:

const [file, setFile] = useState<File>()
const onChange = async (
    imageList: ImageListType,
    addUpdateIndex: number[] | undefined
) => {
    if (imageList[0].file) {
        console.log("first image: ", imageList[0].file) // this line print out the right file object, but setFile NOT working below line
        setFile(imageList[0].file)
    }

    console.log("file: ", file) // this line will print undefined
}
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

When you call setFile(imageList[0].file), a re-render is need to have file updated. Updating a state is an asynchronous task, this why you are getting undifined. To see the updated value of file, you could add the console.log just after calling useState, this way:

const [file, setFile] = useState<File>()
console.log(file); // you will get undifined first, and after calling onChange the updated value

Or, you could use an useEffect, like so:

useEffect(()=>{
 if (file){
   console.log(file)
 }
},[file])
about 4 years ago · Juan Pablo Isaza Relatório

0

I do believe that useState can set any type of object however the problem here that you are setting the file then logging it which 90% work why is that? that's because ReactJs useState sets its state asynchronously

so in order to verify the file object add this to your code

useEffect(()=>{
   console.log(file)
},[file])
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