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)
CodePudding user response:
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]);
CodePudding user response:
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.
CodePudding user response:
event loop , not then ,use async await