1

I would like to fetch data from a URL that is stored in the Firebase database and display the data in my React Native app, I tried some tutorials on Promies and Async/Await but I can't seem to apply them to my problem here is my code:

listenForItems(itemsRef) {
    itemsRef.on('value', (snap) => {
      var items = [];
      snap.forEach((child) => {
        items.push({
          url: child.val().url,
          _key: child.key
        });
      });
      this.setState({ urls: items });
      //this.fetchData(); calling fetch here causes duplicate data
    });
    this.fetchData(); // calling fetch here does not display data
  }

How can I asynchronously display the data using promises or async/await?

KENdi
  • 7,576
  • 2
  • 16
  • 31
Harry
  • 1,021
  • 4
  • 21
  • 41

1 Answers1

0

You should use a boolean flag to indicate that the initial data has been loaded inside 'value'. 'value' will load all the data at once and any changes the data set will cause it to retrigger.

If you don't want it to retrigger, consider using ref.once.

var initialDataLoaded;
listenForItems(itemsRef) {
    itemsRef.on('value', (snap) => {
      var items = [];
      snap.forEach((child) => {
        items.push({
          url: child.val().url,
          _key: child.key
        });
      });
      if(!initialDataLoaded) {
         initialDataLoaded = true;
         this.setState({ urls: items });
         this.fetchData();
      }
    });
  }

You might want to read this https://stackoverflow.com/a/27995609/1405577 comment explaining how to separate 'value' and 'child_added' listeners. And finally check out the Firebase JS SDK documentation for Reference.on

mjabadilla
  • 1,006
  • 14
  • 31