简体   繁体   中英

How to get data from different collections in firebase from react?

So i have 2 collections

1 collection is 'users'. There i have documents (objects) with property 'profile', that contains string. It's id of profile, that is stored in other collection 'roles' as document.

So i'm trying to get this data, but without success. Is there exist join method or something like that? Or i must use promise for getting data from collection roles, and then assign it with agent?

async componentDidMount() {
    firebase
      .firestore()
      .collection('users')
      .orderBy('lastName')
      .onSnapshot(async snapshot => {
        let changes = snapshot.docChanges()

        const agents = this.state.agents
        for (const change of changes) {
          if (change.type === 'added') {
            const agent = {
              id: change.doc.id,
              ...change.doc.data()
            }

            await firebase
              .firestore()
              .collection('roles')
              .doc(change.doc.data().profile).get().then( response => {
                //when i get response i want to set for my object from above this val 
                agent['profile'] = response.data().profile
                //after that i want to push my 'agent' object to array of 'agents'
                agents.push(agent)
                console.log(agent)
                }
              )
          }
        }

        this.setState({
          isLoading: false,
          agents: agents
        })
      })
  }

To do async operation on array of objects you can use promise.all, i have given a example below that is similar to your use case where multiple async operation has to be done

  const all_past_deals = await Promise.all(past_deals.map(async (item, index) => {
     const user = await Users.get_user_info(item.uid);

    const dealDetails = await Deals.get_deal_by_ids(user.accepted_requests || []);

    const test = await Users.get_user_info(dealDetails[0].uid);
return test
 }))

 }

This way you can get data from once api call and make other api call with the obtained data

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM