Home > Mobile >  How to restrict the user from creating more than one doc in firestore database?
How to restrict the user from creating more than one doc in firestore database?

Time:07-22

I have a form on my flutter app where the userr can submit his personal info:


try {
      await FirebaseFirestore.instance
          .collection('users')
          .doc(userID).collection('personalInfo')
          .add(_insertProfInfoToDBToDB.toJson());

This function is triggered by a sunmit button, now the problem is that if the user doesnt have an internet connection for example and he submit this form, then he will get an error that there is no internet connection which is coming from another function


Future<void> _tryConnection() async {
    try {
      final response = await InternetAddress.lookup('Example.com');

      setState(() {
        _isConnectionSuccessful = response.isNotEmpty;
      });
    } on SocketException catch (e) {
      print(e);
      setState(() {
        _isConnectionSuccessful = false;
      });
    }
    if (_isConnectionSuccessful != true){
      Utils.showSnackBar("Please check your internet connection");
    }
  }

but this doesnt restric him from pressing the submit button again and again and again... So what is happening is that once the user gets an internet connection, there will be multiple docs created at the same time inside the 'personalInfo' collection.

My question is how to restrict the user from creating more than one doc inside a collection?

CodePudding user response:

Use setData

Firestore.instance.
  collection('users').
  document('userID').collection('collection name').document('docId')
  set(data, merge: true)

Now this will create a new entry if it doesnt exist and update it if its existing

From the docs

setData(Map<String, dynamic> data, {bool merge: false}) → Future Writes to the document referred to by this DocumentReference. If the document does not yet exist, it will be created. .If merge is true, the provided data will be merged into an existing document instead of overwriting.>

  • Related