简体   繁体   中英

Flatlist not displaying information retrieved from database

I'm trying to display a list of forums the a user has joined into a flatlist, which is firstly retrieved from firestore via an onSnapshot function in my useLayoutEffect as shown below:

useLayoutEffect(() => {
    const unsubscribe = onSnapshot(userRef, (snapshot) => {
      const joinedForums = [];
      if (snapshot.data().myForums.length > 0) {
        snapshot.get("myForums").forEach((forumDoc) => {
          let docRef = doc(db, "forums", forumDoc);

          getDoc(docRef).then((docInf) => {
            joinedForums.push({
              ...docInf.data(),
              id: docInf.id,
            });
          });
        });
      }

      setJoinedForums(joinedForums);
    });

    return () => unsubscribe();
  }, []);

Whenever I load the screen, the flatlist is empty.

Here is the code for my flatlist:

<FlatList
        data={joinedForums}
        renderItem={({ item }) => (
          <TouchableOpacity
            onPress={() => {
              navigation.navigate("ForumDetails", {
                forumId: item.id,
              });
            }}
          >
            <Card>
              <View>
                <Text>{item.id}</Text>
                <Text>Title: {item.title}</Text>
                <Text>Desc: {item.desc}</Text>
                <Text>Created By: {item.createdBy}</Text>
              </View>
              {/* Maybe add a recent message component onSnapshot for each forum */}
              <TouchableOpacity
                onPress={() => {
                  leaveForum(item.id);
                }}
              >
                <Text>Leave</Text>
              </TouchableOpacity>
            </Card>
          </TouchableOpacity>
        )}
      />

Here is a screenshot of the screen:

空平面列表

After having initially researched on the issue, I discovered that updating a state would cause the flatlist to re-render, so I have tried to manually trigger an update to a separate dummy state through a button which then results for in the flatlist displaying the items correctly.

Here is a screenshot of the screen upon manually updating state: 手动状态更新后

I'm not sure where to tweak my code to get the flatlist to render the items on first load, without having to manually trigger a state change.

You should update the state in onSnapshot after rendering new data retrieved from the snapshot.

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