Margok
Margok

Reputation: 55

How to get data in Firebase Firestore from the Reference data type in React Native

Hello I have a collection called Meal. In this collection i used the data type reference to link another collection called Ingredient. Now I'm trying to get the ingredients to the specific meal.

This is my code:

function Meal() {
  const [loading, setLoading] = useState(true); // Set loading to true on component mount
  const [meal, setMeal] = useState([]); // Initial empty array of meal

  useEffect(() => {
    const subscriber = firestore()
      .collection('Meal')
      .onSnapshot((querySnapshot) => {
        const meal = [];
        querySnapshot.forEach(documentSnapshot => {
          meal.push({
            ...documentSnapshot.data(),
            key: documentSnapshot.id,
        });
      });
      setMeal(meal);
      setLoading(false);
    });


    // Unsubscribe from events when no longer in use
    return () => subscriber();
    
  }, []);

  if (loading) {
    return <ActivityIndicator />;
  }


  return (
    <List
      style={styles.container}
      contentContainerStyle={styles.contentContainer}
      data={meal}
      renderItem={({ item }) => (
        <Card style={styles.item}>
          <Text style={styles.title}> {item.Name}  </Text>
          <Layout>
            <Image
              style={{ height: 128, borderRadius: 5, borderWidth: 2, borderColor: 'black', marginHorizontal: -20 }}
              source={{ uri: item.srcImage}}
            />
          </Layout>
          <Text> {item.Ingredient[0].id} </Text>    
        </Card>
      )}
    />
  );
}

The keywords item.Ingredient[0].id and ìtem.Ingredient[0].path are working properly but I can't get the information stored in the collection Ingredient. Do I need another querySnapshot?

Upvotes: 1

Views: 899

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317402

Do I need another querySnapshot?

If you want to read a document in a second collection, it will require a second query. There are no "join" type operations in Firestore, and queries will not follow references automatically.

Upvotes: 1

Related Questions