Chandler Juego
Chandler Juego

Reputation: 19

How do I get the values of each key in Firebase Realtime Database?

Initially, I got just the values of each key, but now I realized that I will be needing the keys themselves and then get the values of those keys. I commented out what I did before.

Database Structure

    // READ LIST OF STORIES (myFirebase.js)
  getListOfStories(location, callWhenFinished) {
      let ref = firebase.database().ref(location)
      ref
      .once("value")
      .then((snapshot) => {
          let listOfStoryKeys = [];
          snapshot.forEach(function(childSnapshot) {
              var key = childSnapshot.key
              listOfStoryKeys.push(key);
          })
          for (var storyKey in listOfStoryKeys) {
              // printing each story key
              console.log(listOfStoryKeys[storyKey])
          }
          callWhenFinished(listOfStoryKeys);
          // var listOfStories = snapshot.val() || []  // all stories or none at all
          // callWhenFinished(Object.values(listOfStories));
      })
      .catch((error) => {
          console.log("Couldn't get list of objects: " + error);
          callWhenFinished([])
      });
  }

 // OTHERPAGE.js Show stories and their values from the DB and into the console 
  displayStoriesOnPage = (stories) => {
    if (stories.length === 0) {
      console.log("Error: Did not get list of stories!");
      return;
    }
    // Initially got all the values of each story;
    // Now need to get values of each story using their keys
    /*
    console.log(stories);
    for (var iStory in stories) {
      const story = stories[iStory]
      console.log("Story: " + story);
      for (var iAttr in story) {
        const attr = story[iAttr];
        console.log("\t " + iAttr + ": " + attr);
      }
    }
    */
    this.setState((state) => {
      return {
        ...state,
        allStories: stories,
      };
    })
  }

Upvotes: 0

Views: 2158

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 600006

If you need both the keys and the values of the stories, one way to do that is to pass two parameters to your callWhenFinished callback:

  getListOfStories(location, callWhenFinished) {
      let ref = firebase.database().ref(location)
      ref
      .once("value")
      .then((snapshot) => {
          let listOfStoryKeys = [],
              listOfStoryValues = [];
          snapshot.forEach(function(childSnapshot) {
              listOfStoryKeys.push(childSnapshot.key);
              listOfStoryValues.push(childSnapshot.val());
          })
          callWhenFinished(listOfStoryKeys, listOfStoryValues);
      })
      .catch((error) => {
          console.log("Couldn't get list of objects: " + error);
          callWhenFinished([], [])
      });
  }

You can also put the keys and values in a single array, giving the key a name that you're not using for any of your other properties (like $key). That'd look something like:

  getListOfStories(location, callWhenFinished) {
      let ref = firebase.database().ref(location)
      ref
      .once("value")
      .then((snapshot) => {
          let listOfStories = [];
          snapshot.forEach(function(childSnapshot) {
              let story = childSnapshot.val();
              story["$id"] = childSnapshot.key;
              listOfStories.push(story);
          })
          callWhenFinished(listOfStories);
      })
      .catch((error) => {
          console.log("Couldn't get list of objects: " + error);
          callWhenFinished([])
      });
  }

No matter which option you use, you can then iterate over the story values/keys in the callback implementation, and access both the key and the property values.

Upvotes: 1

Related Questions