Trying to set React Usestate variable, but it stays empty [duplicate]

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!


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.


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.