What am I doing wrong here? posts state type returns undefined
Error:
TypeError: Cannot read properties of undefined (reading 'map')
Getting posts subcollection from firestore:
const [posts, setPosts] = useState([]);
useEffect(async () => {
const querySnapshot = await getDocs(
query(collectionGroup(db, "posts"), orderBy("createdAt", "desc"))
);
setPosts(querySnapshot.forEach((doc) => doc.data()));
}, []);
Inserting posts data:
<ScrollView>
{posts.map((post, i) => (
<Post post={post} key={i} />
))}
</ScrollView>;
You directly can't make the useEffect hook as a async. For that you need to create a async method and call that method in useEffect hook.
Here is the sample code, that may help you
const [posts, setPosts] = useState([]);
useEffect(() => {
const getData = async () => {
const querySnapshot = await getDocs(
query(collectionGroup(db, "posts"), orderBy("createdAt", "desc"))
);
setPosts(querySnapshot.forEach((doc) => doc.data()));
};
getData();
}, []);
...