0

I am trying to get the data from my firestore database but it tells me that console.log(cities[1]) is undefined. It is logging all the data of console.log(cities) but not when I am trying to get one line. I also tried it with Object.values[cities] - still undefined. And when I log cities[i] in this forEach loop, it gives me all the data. But not after the loop where I actually need it... Is there a possibility to store all the 50 lines and get a specific row with a simple function or method? Because I need to list all the lines as <li>s in HTML.

          const db = firebase.firestore();
          var i = 0;
          var cities = [];
          db.collection('mensen').get().then((snapshot) => {
                snapshot.docs.forEach(doc => {
                    cities[i] = doc.data().city;
                    i++;
                })
          });
          console.log(cities);
          console.log(cities[1]);

That's what I get when I just log cities:

0: "Berlin"
1: "Hannover"
2: "Berlin"
3: "Berlin"
4: "Karlsruhe"
5: "Berlin"
6: "Leipzig"
7: "Hannover"
8: "Stendal"
9: "Karlsruhe"
10: "Pforzheim"
11: "Karlsruhe"
12: "Hannover"
13: "Potsdam"
14: "Leipzig"
15: "Potsdam"
16: "Berlin"
17: "Pforzheim"
18: "Berlin"
19: "Hannover"
20: "Berlin"
21: "Berlin"
22: "Berlin"
23: "Leipzig"
24: "Hannover"
25: "Magdeburg"
26: "Berlin"
27: "Hannover"
28: "Berlin"
29: "Wernigerode"
30: "Hannover"
31: "Berlin"
32: "Berlin"
33: "Garbsen"
34: "Berlin"
35: "Hannover"
36: "Brandenburg"
37: "Wildau"
38: "Potsdam"
39: "Potsdam"
40: "Hannover"
41: "Karlsruhe"
42: "Hannover"
43: "Berlin"
44: "Berlin"
45: "Halberstadt"
46: "Berlin"
47: "Hannover"
48: "Berlin"
49: "Magdeburg"
length: 50
__proto__: Array(0)
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
bucci
  • 1
  • `db.collection('mensen').get()` is asynchronous. You see the data in the array only after you *expand* it in the console, at which point the data was received. But it's not actually there yet at the moment you log the array and first element. – Felix Kling Jan 19 '20 at 21:27
  • See also https://stackoverflow.com/q/37872730/218196 – Felix Kling Jan 19 '20 at 21:28
  • Ahh yea you are right. It works now. Thanks a lot. :) – bucci Jan 19 '20 at 22:12

0 Answers0