Reputation: 165
I'm using reactJS to create a simple social media app. This is the schema of my database:
--- posts (collection)
|
--- uid (documents)
|
--- userPosts (collection)
|
--- postId (documents)
| |
| --- title: "Post Title"
| |
| --- date: September 03, 2018 at 6:16:58 PM UTC+3
|
--- postId (documents)
|
--- title: "Post Title"
I would like posts to be refreshed in real time with onSnapshot method. How to get ALL of my posts? I changed the structure of my database like you see and I don't know how to get my posts that are nested. This is how I did it before when all of my posts were in "posts" collection.
const [posts,setPosts]= useState([]);
useEffect(() => {
db.collection('posts').onSnapshot(snapshot =>{
setPosts(
snapshot.docs.map(doc=>({
id: doc.id,
post : doc.data()
})));
})
}, [])
Upvotes: 1
Views: 582
Reputation: 121
You can access the nested posts by providing the path to it, like this:
const [posts,setPosts]= useState([]);
useEffect(() => {
db.collection('posts').onSnapshot(snapshot =>{
snapshot.docs.map(doc=>({
doc.collection('userPosts').onSnapshot(snapshot =>{
setPosts(
snapshot.docs.map(doc=>({
id: doc.id,
post : doc.data()
})));
});
}));
});
}, []);
Upvotes: 1