Reputation: 33
I'm trying to fetch a value from my firebase DB and I'm using the following code:
export const getCode = async key => {
let ref = await database.ref ('games/' + key).once('value');
console.log(ref);
console.log(ref.code);
return ref;
};
The results I get from each console.log are these:
the ref
returns
Object {
"code": 665195,
"users": Object {
"-MA5m0PrOWUuz-KdcmRx": Object {
"username": "לעג",
},
},
}
but ref.code
returns undefined
I've spent hours on my code and stackoverflow and couldn't find an answer. Hopefully you could.
Upvotes: 0
Views: 78
Reputation: 1558
you didn't use ref.val() to get values.
try
export const getCode = async key => {
let ref = await database.ref('games/' + key).once('value');
const data = ref.val();
console.log(data);
console.log(data.code);
return data.code;
};
Upvotes: 2
Reputation: 126
Shouldn't the ref
variable be returned? You haven't declared anything named code
hence why it's undefined.
export const getCode = async key => {
let ref = await database.ref ('games/' + key).once('value');
return ref.code;
};
You could also do like the cool kids and make this single line if you are gonna use it as it is.
export const getCode = async key => await database.ref ('games/' + key).once('value').code
Upvotes: 0
Reputation: 629
If ref
gets logged as the following:
Object {
"code": 665195,
"users": Object {
"-MA5m0PrOWUuz-KdcmRx": Object {
"username": "לעג",
},
},
}
I suspect that it could be that you're getting a json string as a response, unless your development environment quotes keys by default.
Maybe try let ref = JSON.parse(await database.ref ('games/' + key).once('value'));
Upvotes: 0