Firestore Saving User Data

Standard

Cloud Firestore + Authentication FTW

The last post on this site was about how Firebase’s Cloud Firestore was a great option for saving data, especially in new or prototype applications.

In a previous post I also showed how you can use Firebase’s handy authentication mechanism to easily register and authenticate users to your site.

This post will attempt to show how the Firestore and authentication mechanisms can be combined to store user preference information.

Authentication Recap

In the auth post we saw how easy it was to setup and that, when a user authenticates, they have a unique id when you can then use.

firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in. uid is now available to use
var uid = user.uid;
}
});

The code above shows how we can watch for when a user logs in. After they have logged in we can then use the uid as a unique identifier for each logged in user. The next step is to start creating some data in our Firestore that we can link to this authenticated user each time they log in.

Save User Related Data

Saving user related data e.g. profile information, with Cloud Firestore is easy. Once you have an authenticated user’s unique identifier you can start to save documents in your Firestore with the UID as an identifier. Each time the user logs in you just look up the document in your Firestore to retrieve the related information about this user/login.

firebase.auth().onAuthStateChanged(function(user) {

var dbUser = db.collection('users’)

.doc(user.uid).set(

{

email: user.email,

someotherproperty: ‘some user preference’

});

});

In the code above we wait for the user to log in, retrieve their UID and create a document in the Firestore using the uid as the index. From this point we can add as many properties to this document that we need, and retrieve the information anytime the user logs in.

Simple stuff! Give Firebase a go, you won’t regret it.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.