Reputation: 79
I am trying to get my username from firebase. console.log shows the correct username. But how can I access uName inside of useEffect to show it in my tet component?
useEffect(async () => {
var username = await firebase
.database()
.ref("users/" + authUser + "/name")
.once("value")
.then(function(snapshot) {
return snapshot;
});
var slicedName = JSON.stringify(username);
var uName = slicedName.slice(1, -1);
console.log("USERNAMELOG", uName);
}, []);
Upvotes: 0
Views: 155
Reputation: 6360
The useEffect
hook doesn't allow async/await
functions as the main handler. You can have it as a separate function and execute it within the hook:
async function getData(authUser) {
return firebase
.database()
.ref('users/' + authUser + '/name')
.once('value')
}
useEffect(() => {
getData(authUser)
.then(username => {
const slicedName = JSON.stringify(username)
const uName = slicedName.slice(1, -1)
console.log("USERNAMELOG", uName)
})
}, [])
As for utilizing the uName
, you can set it as component state or a global store if you have one (or context) to be accessible from other components.
EDIT:
If you're using redux
then you should have a dispatch function to be able to update the global state with the uName
. The only that that should change from the snippet above is that you replace console.log
with some dispatch function you create and give the uName
variable as an argument. Once it's in your Redux state, you should be able to propagate that value down to the components that need the value.
Upvotes: 1