Kprmn5555
Kprmn5555

Reputation: 33

Await returns an object, but when fetching the values they're undefined

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

screenshot

I've spent hours on my code and stackoverflow and couldn't find an answer. Hopefully you could.

Upvotes: 0

Views: 78

Answers (3)

Maulik Dhameliya
Maulik Dhameliya

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

jakob_a
jakob_a

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

FrostyZombi3
FrostyZombi3

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

Related Questions