dev1ce
dev1ce

Reputation: 1727

how to add data for all authenticated users in firestore flutter

I was looking for a way to add/upload data (global data) to firestore for all authenticated users of my app. It will be like a "admin app/panel" which can do the job, I guess? I am not really sure because I have not done this and new to firebase firestore.

My previous approach was :- Whenever a new user logins/signin, a local file having all the data (list type of data) will be uploaded to that specific authenticated user's document. If it is an existed user, I won't upload/add the common data again.

So as you can see, it is a very complicated/bad approach. This is the reason I'm looking for a better way like an admin method which can do the job of adding the common data to all users without me checking every-time.

(I even thought of doing it manually, like adding the data manually from firestore website, but there is no way of getting the user uid before authenticating him/her).

Upvotes: 0

Views: 622

Answers (1)

Peter Koltai
Peter Koltai

Reputation: 9734

To execute some logic when a new user is created, setup Firebase Functions and create a function like below (assuming you have a collection called users):

const functions = require('firebase-functions');
const admin = require('firebase-admin');

// trigger on Firebase user creation
exports.onUserCreate = functions.auth.user().onCreate(async (user) => {
    return admin
        .firestore()
        .collection('users')
        .doc(user.uid)
        .set({
            data: 'whatever you need',
        }, { merge: true });
});

Upvotes: 1

Related Questions