You have unlimited access as a PRO member
You are receiving a free preview of 3 lessons
Your free preview as expired - please upgrade to PRO
Recent Posts
- Object Oriented Programming With TypeScript
- Angular Elements Advanced Techniques
- TypeScript - the Basics
- The Real State of JavaScript 2018
- Cloud Scheduler for Firebase Functions
- Testing Firestore Security Rules With the Emulator
- How to Use Git and Github
- Infinite Virtual Scroll With the Angular CDK
- Build a Group Chat With Firestore
- Async Await Pro Tips
How to Avoid Observable Flicker on Initialzation
written by Jeff DelaneyHave you ever noticed that Firebase auth flickers for a split second when refreshing a page? This is an annoying little problem that happens because Firebase must validate the user’s auth state when the library is re-initilized. This is a common problem for any Observable that requires an initialization value from an external API. Fortunately, we can use the RxJS startWith operator - along with with the browser’s localStorage - to solve this problem.
Simple Use Case
Let’s imagine we’re fetching an Observable from Angular’s HTTP client. There might be a second or two of latency on this request, so let’s provide a default value:
import { startWith } from 'rxjs/operators'; |
Then stream will always have a value to unwrap, for example in the HTML:
{{ data | async }} |
Fixing AngularFire Firebase Auth Flicker
In episode 55 we built an Angular Firebase authentication system, but it suffers from this page refresh flicker issue. Let’s make some adjustments to fix it.
In the auth service, we will save the user data to Local Storage whenever the state changes using the tap
operator, then use startWith
to look for an initial value. In other words, if the user is already logged in and they refresh the page it will already have the user details available.
It only takes two additional lines of code to make happen:
import { switchMap, startWith, tap } from 'rxjs/operators'; |
Now our app will start with the user directly in Local Storage instead of waiting for the Firestore data to load over the network.