How to combine two Redux Firebase Cloud Firestore queries? - firebase

I have two redux queries that pull posts from my Firebase Firestore. The first successfully displays all of the posts of the people I'm following:
export function fetchUsersFollowingPosts(uid) {
return ((dispatch, getState) => {
firebase.firestore()
.collection("posts")
.doc(uid)
.collection("userPosts")
.orderBy("creation", "asc")
.get()
.then((snapshot) => {
const uid = snapshot.query.EP.path.segments[1];
const user = getState().usersState.users.find(el => el.uid === uid);
let posts = snapshot.docs.map(doc => {
const data = doc.data();
const id = doc.id;
return { id, ...data, user }
})
for (let i = 0; i < posts.length; i++) {
dispatch(fetchUsersFollowingLikes(uid, posts[i].id))
}
dispatch({ type: USERS_POSTS_STATE_CHANGE, posts, uid })
})
})
}
The second shows all of my own posts.
export function fetchUserPosts() {
return ((dispatch) => {
firebase.firestore()
.collection("posts")
.doc(firebase.auth().currentUser.uid)
.collection("userPosts")
.orderBy("creation", "desc")
.get()
.then((snapshot) => {
let posts = snapshot.docs.map(doc => {
const data = doc.data();
const id = doc.id;
return { id, ...data }
})
dispatch({ type: USER_POSTS_STATE_CHANGE, posts })
})
})
}
Here's where I currently list the users from the people I follow. But how do I combine them so I can show both my posts and those of the people that I'm following in a single FlatList?
function Feed(props) {
useStatusBar('dark-content');
const [posts, setPosts] = useState([]);
const [refreshing, setRefreshing] = useState(false)
useEffect(() => {
if (props.usersFollowingLoaded == props.following.length && props.following.length !== 0) {
props.feed.sort(function (x, y) {
return y.creation.toDate() - x.creation.toDate();
})
setPosts(props.feed);
setRefreshing(false)
}
}, [props.usersFollowingLoaded, props.feed])
return (
<View style={styles.background}>
{posts.length > 0 ?
<View style={styles.containerGallery}>
<FlatList
refreshControl={
<RefreshControl
refreshing={refreshing}
tintColor="white"
onRefresh={() => {
setRefreshing(true);
props.reload()
}}
/>
}
showsVerticalScrollIndicator={false}
numColumns={1}
horizontal={false}
data={posts}
renderItem={({ item }) => (
<View style={styles.containerImage}>
<Card title={item.title} onPress={() => props.navigation.navigate(routes.GOOD_STUFF_DETAIL, { item: item, postId: item.id, uid: item.user.uid, user: item.user,})} showLike={true} author={"Recommended by " + item.user.name} likeItem={item} likeCount={item.likesCount} icon={categories.categories[item.categoryID].icon} timeStamp={timeDifference(new Date(), item.creation.toDate())}/>
</View>
)}
/>
</View>
: <NothingHere title="Follow friends" text="To see their Good Stuff here" icon="search" color="white"/> }
</View>
)
}
const mapStateToProps = (store) => ({
currentUser: store.userState.currentUser,
following: store.userState.following,
feed: store.usersState.feed,
usersFollowingLoaded: store.usersState.usersFollowingLoaded,
})
const mapDispatchProps = (dispatch) => bindActionCreators({ reload }, dispatch);
export default connect(mapStateToProps, mapDispatchProps)(Feed);
Below is my data structure:
Thanks for reading!

Maybe I misunderstood the database structure but AFAIK it doesn't seem possible to combine both queries. From what I see of the database structure you want to retrieve the posts of userB where you (userA) gave a "like". In order to get that information you scan across the path posts/{userUID}/userPosts/{docId}/likes. Given the queries scan different collection ranges I don't see a way to mix them.
Separately, let's assume for the sake of the argument that you already have a list containing the user UIDs of the people you follow. Then, the Firestore query feature that gets closer to the desired behavior are Collection Group queries. Having in mind the structure of the database:
posts
uid1
userPosts
doc1
doc2
uid2
userPosts
docX
docY
Essentially, collection group queries are a way to simultaneously query across all userPosts collections at once. If each document were to have the author ID as a field you would be able to do something like this:
db.collectionGroup("userPosts").where("uid", "in", ListOfFollowedUsers)
This won't totally solve the problem because the in operator clause is limited to 10 values, so you may apply it at most for 10 followed users.
Overall I would suggest to keep the queries separated and merge them in the application code.

Based on your data, and knowing for a fact how limited queries on Firestore are, you need to do that merge on the client.
What I would do is to keep the list on redux and handle the merge on the reducer. You just need to listen to both actions and then merge them as an array on your app.
If you want to avoid the user seeing partial data (eg, you show your own posts and then another refresh just adds your followers post thus the UI will change) you might want to keep two flags (booleans) while you are loading data and show a spinner if both lists haven't been loaded.
Unless you want to refactor your code, then a lot of merging happens on the client.
Also, side node, I would NOT dispatch something on a for loop like you are doing on the first one, because if that triggers a firestore request, then it might get expensive real fast.

Related

How to filter in sub collection's documents (firebase)?

My problem is that I use wrong query to get the date.
const SaveDateBase = async ( e) => {
e.preventDefault()
await setDoc(doc(db, "Users", "Pompy", "Pompy", user.uid), {
displayName: user.displayName,
uid: user?.uid,
modulyPV}).then(()=>{
console.log("moduly", modulyPV)
})
};
useEffect(() => {
const getUsers = async (users) => {
const URC = query(collection(db, "Users").document("Pompy").collection("Pompy"), where("uid", "==", user?.uid));
const data = await getDocs(URC)
setModulyPV(data.docs.map((doc) => ({...doc.data(), id: doc.id})))
}
getUsers();
},[])
The date are saved in date base, and I can successfully update/delete them, but I do something wrong to fetch (read?) them.
I guess is problem with the code.
You can get the data in diff ways, first "Pompy" seems to be your document where you are storing a nested collection then you document "Pompy" So for retrieve that specific document should be something like:
let snapshot = await db
.collection('Users')
.doc('Pompy')
.collection('Pompy')
.get()
snapshot.forEach(doc =>{
console.log('data:', doc.data())
})
Then to query into the nested collection would be something like querying the nested collections.
https://cloud.google.com/firestore/docs/samples/firestore-data-get-sub-collections?hl=es-419#firestore_data_get_sub_collections-nodejs
You can also use collection groups.
https://firebase.google.com/docs/firestore/query-data/queries#collection-group-query
const pompys = query(collectionGroup(db, 'Pompy'), where("uid", "==", user?.uid));

How to access all documents, my all documents only have sub collection in firestore

I have create document like this in react native, I am using rnfirebase library
firestore()
.collection('WaterCanData')
.doc(EntryDate)
.collection('Entries')
.doc(values.customerName)
.set({
CustomerName: values.customerName,
CansOut: values.cansOut,
JarsOut: values.jarsOut,
EmptyCansIn: values.emptyCansIn,
JarsIn: values.jarsIn,
Bottles: values.bottles,
Ice: values.ice
})
.then(() => {
console.log('Entry added!!!!!!!!!');
})
When I try to retrieve EntryDate from WaterCanData Coellection I am not able to fetch it(Document name appears in italic font), So how should I retrive this document which contains a subcollection, Below I have attached my ss of data structure
Data structure
Data structuree
The reason your document appears in italics is because it doesn't currently exist. In Cloud Firestore, subcollections can exist without requiring their parent document to also exist.
Non-existant documents will not appear in queries or snapshots in the client SDKs as stated in the Firebase Console.
This document does not exist, it will not appear in queries or snapshots
If you want to be able to get your entry dates, you need to create the document (which can be empty).
firebase.firestore()
.collection('WaterCanData')
.doc(EntryDate)
.set({}); // an empty document
To create the document at the same time as an entry on it's subcollection, you can use a batched write like so:
const db = firebase.firestore();
const batch = db.batch();
// get references to the relevant locations
const entryDateRef = db
.collection('WaterCanData')
.doc(EntryDate);
const customerRef = entryDateRef
.collection('Entries')
.doc(values.customerName);
// queue the data to write
batch.set(entryDateRef, {});
batch.set(customerRef, {
CustomerName: values.customerName,
CansOut: values.cansOut,
JarsOut: values.jarsOut,
EmptyCansIn: values.emptyCansIn,
JarsIn: values.jarsIn,
Bottles: values.bottles,
Ice: values.ice
})
// make changes to database
batch.commit()
.then(() => {
console.log('Entry added!!!!!!!!!');
});
This will then allow you to list all of the entry dates in your database using something like:
firebase.firestore().collection('WaterCanData')
.get()
.then((querySnapshot) => {
querySnapshot.forEach(doc => {
const entryDate = doc.id;
// const customerEntriesRef = doc.ref.collection('Entries');
console.log('Entry date found: ' + entryDate);
}
});
If (as an example) you wanted to also find how many entries were linked to a given date, you would need to also query each subcollection (here the code gets a little more confusing).
firebase.firestore().collection('WaterCanData')
.get()
.then((querySnapshot) => {
const fetchSizePromises = [];
// for each entry date, get the size of it's "Entries" subcollection
querySnapshot.forEach(doc => {
const entryDate = doc.id;
const customerEntriesRef = doc.ref.collection('Entries');
// if this get() fails, just store the error rather than throw it.
const thisEntrySizePromise = customerEntriesRef.get()
.then(
(entriesQuerySnapshot) => {
return { date: entryDate, size: entriesQuerySnapshot.size }
},
(error) => {
return { date: entryDate, size: -1, error }
}
);
// add this promise to the queue
fetchSizePromises.push(thisEntrySizePromise)
}
// wait for all fetch operations and return their results
return Promise.all(fetchSizePromises);
})
.then((entryInfoResults) => {
// for each entry, log the result
entryInfoResults.forEach((entryInfo) => {
if (entryInfo.error) {
// this entry failed
console.log(`${entryInfo.date} has an unknown number of customers in its Entries subcollection due to an error`, entryInfo.error);
} else {
// got size successfully
console.log(`${entryInfo.date} has ${entryInfo.size} customers in its Entries subcollection`);
}
}
});
Using below code you can console every document id inside waterCanData collection. In your database you have only one document, then it will console your document id. (10042021)
firestore()
.collection('WaterCanData')
.get()
.then((querySnapshot) => {
querySnapshot.forEach((doc) => {
console.log(doc.id)
});
})

Chaining Firebase Firestore documents/collections

So, I have a Firestore database group like so.
companies > acme-industries > items > []
OR
collection > document > collection > document
Would it be better to just store all items inside a base collection and then add a string value to each item that defines what company it goes too? Then just query the items collection for all items linked to that company?
I am trying to retrieve the items and run them through a forEach in my firebase function. I have tried two different approaches and watched multiple videos and still am not getting results.
First Attempt Code Block
This resulted in a 500 Server Error with no explanation returned.
const itemQuerySnapshot = db.collection('companies').doc(data.userData.company).collection('items').get();
const items: any = [];
itemQuerySnapshot.forEach((doc:any) => {
console.log('doc', doc.data());
items.push({
id: doc.id,
data: doc.data()
});
});
response.json(items);
Second Attempt Code Block
This resulted in the No Such Documents! being returned
const itemRef = db.collection('companies').doc(data.userData.company).collection('items');
itemRef.get().then((doc:any) => {
if(!doc.exists) {
response.send('No such documents!');
} else {
response.send('Document Data: '+ doc.data());
}
}).catch((err:any) => {
response.status(500).send(err);
});
I am expecting something like an array of all the items to be returned from this call. I'm completely new to Firebase Firestore, what am I missing here?
UPDATE
I replaced my code with a third attempt code block and I got success with the console.log(doc.data()). However, the items object still returns empty. Is this because it's returning before the for each is done? If so, how would you prevent that to ensure every item that should be returned is?
const items: any = [];
const userRef = db.collection("companies").doc(data.userData.company);
const itemsRef = userRef.collection("items");
itemsRef
.get()
.then((snapshot: any) => {
snapshot.forEach((doc: any) => {
console.log(doc.data());
items.push({
id: doc.id,
data: doc.data()
});
});
})
.catch((err: any) => {
response.status(500).send(err);
});
response.json(items);
How would you add one more document into the mix? Say you want to get a single item. How would you do that? The following always results in Item does not exist being returned from my function.
const companyRef = db.collection('companies').doc(data.userData.company);
const itemRef = companyRef.collection('items');
const item = itemRef.where('number', '==', itemSku).get();
I must be doing something incredibly wrong here because all the videos are telling me it's incredibly easy to fetch data from Firestore. But I have yet to see that.
get returns a Promise , the callback of then function will be called once the data ready from firestore .
the line response.json(items); will be called before the items array collected correctly.
you need to move this line inside the then callback
checkout this :
.then((snapshot: any) => {
snapshot.forEach((doc: any) => {
console.log(doc.data());
items.push({
id: doc.id,
data: doc.data()
});
});
response.json(items); //items ARRAY IS READY , YOU CAN SEND YOUR RESPONSE HERE
})

How to display some data from firebase in react-native

I want to display some data from firebase, the problem is that I don't know how to do this after trying many things.
My firebase datbase looks like this:
Now I want to put this data into a calender, so I want only the date from one userID. So I can get only one date, and then use it.
How can I do this?
I now use this:
componentDidMount() {
let userId = firebase.auth().currentUser.uid;
firebase.database().ref('poolog/' + userId ).on('value', (snapshot) => {
this.setState({abc: snapshot.val().childData});
let data = snapshot.val();
let datums = Object.values(data);
this.setState({datums});
});
};
And then I want to render it:
render(){
return(
<View>
<Text>{
this.state.datums
}</Text>
</View>
);
}
basically this way i put every single day of an user in an array so you can access any day.And then you can access each day by an index.
componentDidMount(){
var days = []
firebase.database().ref('poolog/' + userId ).once('value', (snap) => {
snap.forEach((data)=>{
days.push({
day:data.key,
availableHours:data.val()
})
})
console.log(days)
//this.setState({datums:days})
})
}

How to get documents with array containing a specific string in Firestore with React-Native

I am just getting started with Firebase and am trying to determine how to best structure my Firestore database.
What I want is to find all documents from an 'events' collection where 'participants' (which is an array field on each event document which contains objects with keys 'displayName' and 'uid') contains at least one matching uid. The list of uids I am comparing against will be the users' friends.
So in more semantic terms, I want to find all events where at least one of the participants of that event is a 'friend', using the uid of the event participants and of the users friends.
Hope I haven't lost you. Maybe this screenshot will help.
Here is how I've designed the 'events' collection right now
Would a deep query like this doable with Firestore? Or would I need to do the filtering on client side?
EDIT - added code
// TODO: filter events to only those containing friends
// first get current users friend list
firebase.firestore().doc(`users/${this.props.currentUser.uid}`)
.get()
.then(doc => {
return doc.data().friends
})
.then(friends => { // 'friends' is array of uid's here
// query events from firestore where participants contains first friend
// note: I plan on changing this design so that it checks participants array for ALL friends rather than just first index.
// but this is just a test to get it working...
firebase.firestore().collection("events").where("participants", "array-contains", friends[0])
.get()
.then(events => {
// this is giving me ALL events rather than
// filtering by friend uid which is what I'd expect
console.log(events)
// update state with updateEvents()
//this.props.dispatch(updateEvents(events))
})
})
I am using React-Native-Firebase
"react-native": "^0.55.0",
"react-native-firebase": "^4.3.8",
Was able to figure this out by doing what #Neelavar said and then changing my code so that it chains then() within the first level collection query.
// first get current users' friend list
firebase.firestore().doc(`users/${this.props.currentUser.uid}`)
.get()
.then(doc => {
return doc.data().friends
})
// then search the participants sub collection of the event
.then(friends => {
firebase.firestore().collection('events')
.get()
.then(eventsSnapshot => {
eventsSnapshot.forEach(doc => {
const { type, date, event_author, comment } = doc.data();
let event = {
doc,
id: doc.id,
type,
event_author,
participants: [],
date,
comment,
}
firebase.firestore().collection('events').doc(doc.id).collection('participants')
.get()
.then(participantsSnapshot => {
for(let i=0; i<participantsSnapshot.size;i++) {
if(participantsSnapshot.docs[i].exists) {
// if participant uid is in friends array, add event to events array
if(friends.includes(participantsSnapshot.docs[i].data().uid)) {
// add participant to event
let { displayName, uid } = participantsSnapshot.docs[i].data();
let participant = { displayName, uid }
event['participants'].push(participant)
events.push(event)
break;
}
}
}
})
.then(() => {
console.log(events)
this.props.dispatch(updateEvents(events))
})
.catch(e => {console.error(e)})
})
})
.catch(e => {console.error(e)})
})

Resources