Reputation: 259
I've written a function that gets data from my firestore, filters through it, and returns data posted only by the logged-in user. The data, in this case, are gig listings:
authListener() {
auth().onAuthStateChanged((user) => {
if (user) {
this.setState(
{
userDetails: user
},
() =>
axios
.get(
"https://us-central1-gig-fort.cloudfunctions.net/api/getGigListings"
)
.then((res) => {
let filteredGigs = res.data.filter((gig) => {
return gig.user === this.state.userDetails.uid;
});
this.setState({
filterGigs: filteredGigs
});
})
);
} else {
this.setState({
userDetails: null,
});
console.log("no user signed in");
}
});
}
However, when I render this data, I want it to be subscribed in real time to database changes, and I also want to be able to access the document id. In order to do this, I want to change this function to use the onSnapshot()
method, here's my (rough) attempt:
authListener() {
auth().onAuthStateChanged((user) => {
if (user) {
this.setState(
{
userDetails: user
},
() =>
firebase.firestore().collection('gig-listing').onSnapshot(querySnapshot=> {
let filteredGigs = querySnapshot.filter(gig => {
return gig.user === this.state.userDetails.uid;
})
})
this.setState({
filterGigs: filteredGigs
});
})
);
This code isn't working and I have a feeling there's more than one issue, but the main error I'm getting back is querySnapshot.filter is not a function
. Can anyone suggest how to re-configure my code so I can use the snapshot method, instead of my axios get request?
Upvotes: 0
Views: 398
Reputation: 673
If you take aa look at the docs, the onSnapshot()
method returns a QuerySnapshot
. The QuerySnapshot
has a docs
property which has all the documents in the snapshot. So you can filter them like this :
firebase.firestore().collection('gig-listing').onSnapshot(querySnapshot => querySnapshot.docs.filter(d => {
const data = d.data()
// Do whatever with data
})
Upvotes: 1
Reputation: 317768
querySnapshot is a QuerySnapshot object. As you can see from the API documentation, there is no method filter
on that object. If you want something to filter, perhaps you meant to use its docs property, which is an array of QueryDocumentSnapshot objects that contain the actual document data. So, maybe something more like this is what you want:
let filteredGigs = querySnapshot.docs.filter(snapshot => {
return snapshot.data().user === this.state.userDetails.uid;
})
Upvotes: 1