How to use Stream callbacks in Cloud Firestore - firebase

I have a few questions (I am new to Dart) w.r.t the code below which I found. What I am trying to achieve:
1) Write more than one line in the brackets for errors. But I get error saying 'set literals were supported upto 2.2....'. It would also be good to know the list of possible errors so I can alert the user accordingly.
2) Increment a counter pertaining to number of documents and keep storing document id's in one variable, by overwriting the last value if more than one document is found. I am trying to check that there should only be one document and take action if counter goes to 2.
void _checkIfAdmin() {
Firestore.instance
.collection('Admin')
.where('Email', isEqualTo: widget._user.email)
.snapshots()
.handleError((error)=>{
//
})
.listen((data) => data.documents.forEach((doc) => gpCounter+=1)); // Store document id?
print('Counter: $gpCounter');
}
Here I am getting printed gpCounter=0 when I know there are two documents in there. I tried adding async/await in the function but it seems the firebase statement does not return any future so I get a warning to use await only for futures.

I will try to address as many issues as I could understand in your question. If you have any other issues, you should probably ask another question.
Set literals: the syntax for anonymous functions is () {} and not () => {}.
() => is a shorthand syntax to return the value of a single expressions and in your case, you are returning a Set in your anonymous functions because {} create Set's (or Map's if you have colons in there).
The solution for this is (error) { ... }.
You print your gpCounter value synchronously, however, you are listening to a Stream.
Because of that, you should move your print statement to your listen function:
.listen(data) {
print('Counter: ${data.documents.length}');
})

Related

How to create a document if the document doesn't exist or else don't do anything?

I Wanted To Ask If It Is Possible To Make A New Document With A UID If It DOESN'T Exist But if it exists NOT To Do Anything (and if possible return an error) In Firestore. (In Modular Javascript)
And If It Is Possible How?
Note: I Already Read This Question:StackOverFlow 46888701 But It Doesn't Fit My Requirements because after creating the document I want to be able to update it too.
Edit: I Wanted To Know Without Using getDoc because when i use it acts like a read and i don't want to spend lots of my no of reads from my limit.
You should first try to get the document and check if it exists then proceed to your document set/update. See sample code below:
import { doc, getDoc } from "firebase/firestore";
const docRef = doc(db, "<collection>", "<UID>");
const docSnap = await getDoc(docRef);
if (docSnap.exists()) {
console.log("Document exist!");
// Throws an error.
throw new Error('Document Exist!');
} else {
await setDoc(docRef, {
// Document Data
});
}
For more relevant information, check out these documentations:
Get a document
Update a document
Set a document
Edit:
If you don' t want to use getDoc then you have the option to use updateDoc, it will produce an error but you can still execute a setDoc method on the catch method. On this approach, you're doing a fail-safe practice that you're responding in the event of failure. See code below:
const docRef = doc(db, "<collection>", "<UID>");
// Produces error log if no document to update
updateDoc(docRef, {
// document data
})
.catch((error) => {
// console.log(error);
setDoc(docRef, {
// document data
});
});
According to the documentation, an update is just a write operation:
Charges for writes and deletes are straightforward. For writes, each set or update operation counts a single write.
We have established that an update is just a write operation (there's no reading involved). A write is a change in a document, since you're not changing anything because the document didn't exist then you won't be charged at all.
In web version 9, the function that can help you create a document is named setDoc(), which creates or overwrites a document at a specific document reference.
How to create a document if the document doesn't exist or else don't do anything?
If you want to achieve that, you have to check if the document already exists. If it doesn't exist, create it using setDoc(), otherwise, take no action, but do not use the updateDoc() function in this case.
Remember that the updateDoc() function helps only when you want to update some fields of a document without overwriting the entire document. If the document doesn't exist, the update operation will fail.
Edit:
According to your edited question, please note that there is no way you can know if a document exists, without checking it explicitly. You can indeed not do that check, but you'll end up overwriting the document over and over again. Please also note, that a write operation is more expensive than a read operation. So that's the best option that you have.

Trying to filter down chat messages using Flutter and Firestore

I'm trying to create a Blocked Users list in my chat app using the latest versions of Flutter Beta channel (1.23.0-18.1.pre) and cloud_firestore 0.14.3.
Here's my data structure:
At first, I tried something like this (Hardcoded just to test), by filtering the messages I'm querying from Firestore. Firebase doesn't like this.
query: firestore.collection('messages')
.where('userId', whereNotIn: ['123456789', '987654321'] )
.where('hashtag', isEqualTo: hashTag)
.orderBy('submittedAt', descending: true),
reverse: true,
I get this error:
E/FLTFirestoreMsgCodec(24331): java.lang.IllegalArgumentException: Invalid query. You have an inequality where filter (whereLessThan(), whereGreaterThan(), etc.) on field 'userId' and so you must also have 'userId' as your first orderBy() field, but your first orderBy() is currently on field 'submittedAt' instead.
After doing some more reading, filtering on the client-side by just hiding the messages actually better suits my needs.
Unfortunately, I'm running in circles. I'm currently thinking I would map a stream to a list, and then do something like this:
if (message.userId is in the list) {
isBlocked = true;
} else {
isBlocked = false;
}
And then filtering out the messages if isBlocked is true. I tried hardcoding the values for that and it worked. BTW, Sorry for the pseudocode, but I deviated so many times that now I'm simply lost.
I was wondering if this was the correct approach? Any suggestions would be rad. I also tried using a future list from a stream but I couldn't get that to work either.
Future<Stream<List<BlockedUser>>> getBlockedIds() async {
Stream<List<BlockedUser>> list;
Stream<QuerySnapshot> snapshot = FirebaseFirestore.instance.collection('user').doc('id').collection('blocked').snapshots();
list = snapshot.map((query) => query.docs.map(
(doc) => BlockedUser(
id: doc.data()['id'])
).toList());
return list;
}
I can't get that to work since I don't know what to do with that list.
Thanks, everyone!

Firebase, add unique id and data - promise error add/set is not a function

How can I add document data as well as a unique id?
I am using:
if (fcmToken) {
firebase
.firestore()
.collection("users")
.add(fcmToken)
.set({
year
})
.then(function() {
return true;
})
.catch(function(error) {
return false;
});
}
I get the error:
Possible Unhandled Promise Rejection (id: 0):
TypeError: _reactNativeFirebase.default.firestore(...).collection(...).add(...).set is not a function
Chaining set after add doesn't really make any sense. The are independent operations, and both return a promise that resolves after the work is complete. The error you're seeing is telling that the promise returned by add doesn't have a method called set.
Just use one or the other, not both.
Using add, you can specify the entire document's content with the object you pass to it, and it will be assigned a random unique ID.
If you want to generate your own ID, build a DocumentReference to the document you want to create, and set it directly. For example:
firebase.firestore().collection("users").doc(fcmToken).set(...)
Use add instead of set. It will return the generated id.
https://firebase.google.com/docs/reference/js/firebase.firestore.CollectionReference.html?authuser=0#add

Removing specific map/object from array in firebase

I'm experimenting with arrays and maps/objects in firestore. I wondered how can I remove a specific map from the array.
I tried something like this:
await Firestore.instance.collection('users').document(interestedInID).get().then((val){
return val.data['usersInterested'].removeWhere((item)=>
item['userID'] == userID
);
}).catchError((e){
print(e);
});
but I get this error in terminal:
Unsupported operation: Cannot remove from a fixed-length list
I don't really understand what it means. I did some googling and fixed-length list is exactly what it says. It's a list that has a fixed length and it can't be changed, but fixed-length list has to be declared explicitly. Growable list on the other hand doesn't need to be declared.
I haven't declared the fixed-length list in my firestore, yet it keeps saying that I can't remove elements from it. I can add / push elements however and remove them using:
'key': FieldValue.arrayRemove([value])
but I can't figure out how to remove the element based on a specific condition. In this case an userID.
Any suggestions?
Thanks a lot!
Figured it out.
await Firestore.instance.collection('users').document(interestedInID).updateData({
'usersInterested': FieldValue.arrayRemove([{}.remove(userID)])
});
I'm not sure, but I think get() simply allows you to read the document, but doesn't allow to make any changes to it.
Anyways, now it works
This may be a workaround:
You fetch your specific Array with key: values from Firebase
Put that in a temporary reference List in dart
Remove your specific Map from the reference List, like you did before
Update data in Firebase like so:
// make a reference List
List<Map> _modifiedUsersInterested = List();
// ... (fetch your Array first from Firebase, put those items in the reference List)
// remove the right Map from the reference List
_modifiedUsersInterested.removeWhere((item) => {
item['userID'] == userID
});
// set the reference List as your array in Firebase
await Firestore.instance
.collection('users')
.document(interestedInId)
.updateData(
{'usersInterested': _modifiedUsersInterested}
);

Retrieve values from firebase database in conversation flow

I am trying to grab information from my firebase database after a particular intent is invoked in my conversation flow.
I am trying to make a function which takes a parameter of user ID, which will then get the highscore for that user, and then say that users highscore back to them.
app.intent('get-highscore', (conv) => {
var thisUsersHighestscore = fetchHighscoreByUserId(conv.user.id);
conv.ask('your highest score is ${thisUsersHighestScore}, say continue to keep playing.');
});
function fetchHighscoreByUserId(userId){
var highscoresRef = database.ref("highscores");
var thisUsersHighscore;
highscoresRef.on('value',function(snap){
var allHighscores= snap.val();
thisUsersHighscore = allHighscores.users.userId.highscore;
});
return thisUsersHighscore;
}
An example of the data in the database:
"highscores" : {
"users" : {
"1539261356999999924819020" : {
"highscore" : 2,
"nickname" : "default"
},
"15393362381293223232222738" : {
"highscore" : 78,
"nickname" : "quiz master"
},
"15393365724084067696560" : {
"highscore" : "32",
"nickname" : "cutie pie"
},
"45343453535534534353" : {
"highscore" : 1,
"nickname" : "friendly man"
}
}
}
It seems like it is never setting any value to thisUsersHighScore in my function.
You have a number of issues going on here - both with how you're using Firebase, how you're using Actions on Google, and how you're using Javascript. Some of these issues are just that you could be doing things better and more efficiently, while others are causing actual problems.
Accessing values in a structure in JavaScript
The first problem is that allHighscores.users.userId.highscore means "In an object named 'allHighscores', get the property named 'users', from the result of that, get the property named 'userId'". But there is no property named "userId" - there are just a bunch of properties named after a number.
You probably wanted something more like allHighscores.users[userId].highscore, which means "In an object named 'allHighscores', get the property named 'users', fromt he result of that, get the property named by the value of 'userId'".
But if this has thousands or hundreds of thousands of records, this will take up a lot of memory. And will take a lot of time to fetch from Firebase. Wouldn't it be better if you just fetched that one record directly from Firebase?
Two Firebase Issues
From above, you should probably just be fetching one record from Firebase, rather than the whole table and then searching for the one record you want. In firebase, this means you get a reference to the path of the data you want, and then request the value.
To specify the path you want, you might do something like
var userRef = database.ref("highscores/users").child(userId);
var userScoreRef = userRef.child( "highscore" );
(You can, of course, put these in one statement. I broke them up like this for clarity.)
Once you have the reference, however, you want to read the data that is at that reference. You have two issues here.
You're using the on() method, which fetches the value once, but then also sets up a callback to be called every time the score updates. You probably don't need the latter, so you can use the once() method to get the value once.
You have a callback function setup to get the value (which is good, since this is an async operation, and this is the traditional way to handle async operations in Javascript), but you're returning a value outside of that callback. So you're always returning an empty value.
These suggest that you need to make fetchHighScoreByUserId() an asynchronous function as well, and the way we have to do this now is to return a Promise. This Promise will then resolve to an actual value when the async function completes. Fortunately, the Firebase library can return a Promise, and we can get its value as part of the .then() clause in the response, so we can simplify things a lot. (I strongly suggest you read up on Promises in Javascript and how to use them.) It might look something like this:
return userScoreRef.once("value")
.then( function(scoreSnapshot){
var score = scoreSnapshot.val();
return score;
} );
Async functions and Actions on Google
In the Intent Handler, you have a similar problem as above. The call to fetchHighScoreByUserId() is async, so it doesn't finish running (or returning a value) by the time you call conv.ask() or return from the function. AoG needs to know to wait for an async call to finish. How can it do that? Promises again!
AoG Intent Handlers must return a Promise if there is an asyc call involved.
Since the modified fetchHighScoreByUserId() returns a Promise, we will leverage that. We'll also set our response in the .then() part of the Promise chain. It might look something like this:
app.intent('get-highscore', (conv) => {
return fetchHighscoreByUserId(conv.user.id)
.then( function(highScore){
conv.ask(`Your highest score is ${highScore}. Do you want to play again?`);
} );
});
Two asides here:
You need to use backticks "`" to define the string if you're trying to use ${highScore} like that.
The phrase "Say continue if you want to play again." is a very poor Voice User Interface. Better is directly asking if they want to play again.

Resources