0

I have written this code to access my variable outside the function.The value of res outside the function is undefined. the outside console.log should print the url which is assigned to res inside the function. I will use this response in my anchor tag to open the url in res variable. What am I doing wrong?

const firebaseApp = initializeApp(firebaseconfig)
const storage = getStorage(firebaseApp)
var res;
  const downloadurl = function() { getDownloadURL(ref(storage, 'files/linpeas.txt'))
    .then((url) => {
       res = url
       console.log(res)
    })};
      
console.log(res)
12
  • Do you call downloadurl()? Commented Mar 25, 2022 at 18:55
  • Yes I am calling it in Button Commented Mar 25, 2022 at 18:56
  • I do not see nothing wrong with the code. The console.log() outside de function should return undefined but the one inside the function should return the info. Try adding a .catch() to show if there is some error Commented Mar 25, 2022 at 19:11
  • the outside console.log is printing undefined whereas it should print the url the is assigned to res inside the function Commented Mar 25, 2022 at 19:15
  • Can you please provide more information? I think the function getDownloadURL is async so that the value (url) will be assigned to res when the function is executed or completed but the console log will run before executing the function. Commented Mar 25, 2022 at 19:27

1 Answer 1

1

Try using the useState() to store res and the useEffect() to update res when this changes;

const firebaseApp = initializeApp(firebaseconfig)
const storage = getStorage(firebaseApp)
const [res, setRes] = useState();

const downloadurl = () => { getDownloadURL(ref(storage, 'files/linpeas.txt'))
    .then((url) => {
       setRes(url);
       console.log(res)
    })
    .catch((error) => console.log(error));
};
      
useEffect(() => {
    console.log(res);
  }, [res]);
Sign up to request clarification or add additional context in comments.

4 Comments

not working again same undefined
I am not using useEffect as I am using this url in anchor tag to move to the url
If you can put more code or give more details would be useful
I have updated the question

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.