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

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

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 Relatório

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