简体   繁体   中英

getting a array object but cant access the elements inside it

Im trying to get all the posts of the people that are followed by the user, but Im getting an array of objects and I can't access the objects inside it. here is my code:

initialize the states:

const [following, setFollowing] = useState([]);
const [allPosts, setAllPosts] = useState([]);

create the collection reference and get the data, this data is the Ids of the people the user follows :

const followingColRef = collection(db, "users", uid, "following");

  useEffect(() => {
    onSnapshot(followingColRef, (snapshot) => {
      setFollowing(
        snapshot.docs.map((item) => ({ ...item.data(), id: item.id }))
      );
    });
  }, []);

and then here im trying to get all the posts posted by every user id in the array created above ( following ):

useEffect(() => {
    const array = [];
    following.map((user) => {
      const postsColRef = collection(db, "users", user.id, "posts");

      onSnapshot(postsColRef, (snapshot) => {
        array.push(
          snapshot.docs.map((item) => ({ ...item.data(), id: item.id }))
        );
      });
    });
    setAllPosts(array);
  }, [following]);
  console.log(allPosts);

when I open the data logged into the console it would be something Like:

[
    [
        {
            "likes": 2,
            "user": "Some Name",
            "comments": 1,
            "body": "Somthing...",
            "uid": "cU1h2uh5CTMGKEKD4Wa986YUDqp1",
            "created_at": {
                "seconds": 1664450450,
                "nanoseconds": 779000000
            },
            "id": "Z7OcjSIY8OYKpbC1pdyq"
        }
    ]
]

but if I try and access allposts[0] I get undefined

so why is this happening and how can I remove the top layer array since it's not doing anything important

any help would be great thank

Probably because allPosts[0] is undefined at the time you try to access it.

You can try two methods to achieve what you want

to remove the outer array you can try setting allPosts like this instead setAllPosts(array[0])

Then try a new useEffect like below to get around the returning undefined issue.

useEffect(() => {
console.log(allPosts[0])
}, [allPosts]);

Alternatively instead of everything above you can achieve removing the outer array and accessing the data in one go by doing this

useEffect(() => {
setAllPosts(prevPost => prevPost[0]);
console.log(allPosts[0])
}, [allPosts]);

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