0

I know this is probably really simple - but I'm horrendous at JavaScript and can't figure this out. Have been looking through other StackOverflow posts for a good hour and all "solutions" don't seem to work.

I have the below function - which returns what's shown in the image - but i'm not sure how to convert this into a json object that I can actually work with on the frontend.

Anyone know how to modify this in order to accomplish that?

  getTools = ({id}) => {
    let ref = this.write.collection('tools').doc(id)
    let results = []
    ref.onSnapshot(snapshot => {
      const id = snapshot.id
      const data = snapshot.data()
      results.push({...data, id})
      });
    return results
  }

enter image description here

jmelm93
  • 145
  • 1
  • 10
  • `getTools` returns an empty array because it's populated only later in that callback function that is passed to `onSnapshot`. You need to refactor it somehow. There's too little code to give any more detailed advice. – tromgy Jan 11 '22 at 02:22
  • Hi, did you try [this](https://stackoverflow.com/questions/53569696/retrieve-data-from-firestore-as-json), if you did, then please do tell the things that you have already tried and the error that you are receiving if any. – Zeenath S N Jan 11 '22 at 07:10

1 Answers1

0

Its returning nothing because the onSnapshot is an asynchronous event.

async function getTools(id) {
 let ref = this.write.collection('tools').doc(id)
 let results = await ref.onSnapshot(snapshot => snapshot.data()}
 return results;

}

Something like that.

Nosillock
  • 51
  • 3