0

i'm trying to do something in react and i got stuck .. i don't know why this is happening, i can't explain myself.

let content = null;
storage.ref().child(snapshot.val().content).getDownloadURL().then(url => content = url ); // setting value

console.log('content', content); // returns initial value, in my case, null. why?

Line 19

https://pastebin.com/UkJyJihB

Thanks!

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807

1 Answers1

3

Your action is asynchronous. It means that 'then' function fires only when getDownloadURL() is finished. But console.log fires immidiately, when the content is null yet. So if you want to do something with content, you should do it inside 'then' callback:

let content = null;
storage.ref().child(snapshot.val().content).getDownloadURL()
.then(url => {
   content = url; 
   console.log('content', content);
} ); 
Alex Borodin
  • 1,555
  • 12
  • 26
  • Yeap, now it's working. But another little question, how I can make to be in real time? For example if I change some value from firebase console, I want in my project to be displayed without to refresh the page. Thanks for your time, Alexander! – Danaila Catalin Aug 12 '17 at 11:51
  • For real-time actions, you should use websockets instead of a http requests. Here is popular library for it with demos and docs https://socket.io – Alex Borodin Aug 12 '17 at 11:54