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

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

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 Denunciar

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 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