Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

133
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!