1

I have a firebase realtime database. I would like to write a query and save the data to an array and work with later. Can I do it somehow? This code works nicely, just need to save it somehow for later. Object / map would be great, but an array works too. My half-code is here:

map = new Map();
var rootRef = firebase.database().ref("locations/map");
rootRef.once("value", function(snapshot) {
  snapshot.forEach(function(child) {
    console.log(child.key+": "+child.val().value);
    map.set(child.key, child.val().value);
  });
});
console.log(map);

It works fine, but if i try

console.log(map.get(0));

It's undefined. It's need to this for:

 for (i = 0; i < someaarray.data.length; i++) {
  if (someaarray.data[i].id == map.get(id))
  {
    someaarray.data[i].value = map.get(value);
  }
}

1 Answer 1

1

You need to return a promise since the fetching data is asynchronous, therefore try the following:

function getData() {
return new Promise((resolve, reject) => {
let map = new Map();
var rootRef = firebase.database().ref("locations/map");
rootRef.on("value", function(snapshot) {
  snapshot.forEach(function(child) {
    console.log(child.key+": "+child.val().value);
    map.set(child.key, child.val().value);
    resolve(map);
   });
  });
 });
}

Then when you need to use the map, you need to do the following:

getData().then((value) => {
  console.log(value.get(0));
 });
});

Check here for more info:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! I've tried your code, but the "console.log(value.get(0));" is undefined. :(
is child.key equal to 0? Because inside get() you need to write the key. Do console.log(value)

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.