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

131
Vistas
Trying to set React Usestate variable, but it stays empty

I am new to React and I don't understand this:

I write

const [imageURL,setImageURL] = useState('');

and

 
var temp = "https://" + response.value.cid + ".ipfs.dweb.link/" + response.value.files[0].name;
                                setImageURL(temp)
                                console.log("Set ImageURL to: ", temp);
                                console.log("imageURL shows: ", imageURL);

But am obviously missing the point, because I get an empty variable imageURL:

enter image description here

Would appreciate if someone could explain this to me :) Thanks!

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You can't get the latest state right away in react. when you are setting your state, it's an async operation and it won't give you the value right away in the next line. In order to execute sth based on the latest change in your state, you need to use useEffect like this:

const [imageURL,setImageURL] = useState('');
let temp = "https://" + response.value.cid + ".ipfs.dweb.link/" + response.value.files[0].name;
console.log("Set ImageURL to: ", temp);
setImageURL(temp);

//The latest change would show up inside useEffect here
useEffect(() => {
  console.log("imageURL shows: ", imageURL);
}, [imageURL])

the code inside useEffect would execute everytime your state updates since you pass your state as a dependency there. Go search for useEffect. there are numerous resources out there about that.

about 4 years ago · Juan Pablo Isaza Denunciar

0

That empty string you are passing into the useState() function, is the value first assigned to imageURL. You need to call setImageURL() to set it as you want, or pass in a specific initial value.

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