Angular Bug Fix: Lazy Evaluation for Tenant Data

Ever had a bug that only appears on first load but disappears after a page refresh? I just fixed one. Here's the exact problem I had a reusable utility to read tenant data from localStorage and use it across the app — including in a ThemeService to apply tenant-specific themes: Typescript ❌ The problematic pattern export const LOGGED_USER_TENANT = (() => {  try {   return JSON.parse(localStorage.getItem('loginUserTenant') || '{}');  } catch {   return null;  } })(); // In ThemeService applyTenantTheme(): void {  const loginUserTenant = LOGGED_USER_TENANT; // always null on first load! } On first load → LOGGED_USER_TENANT was always null. After page refresh → it worked perfectly. Why? This pattern is called an IIFE (Immediately Invoked Function Expression). It runs the moment the module is imported — during Angular's bootstrap phase — which happens BEFORE the login flow writes anything to localStorage. So the value gets frozen as null for the entire session. No matter when you call applyTenantTheme(), it reads the same stale null snapshot from import time. ✅ The fix — just remove the IIFE, make it a plain function: Typescript ✅ Lazy evaluation — reads fresh on every call export const LOGGED_USER_TENANT = () => {  try {   return JSON.parse(localStorage.getItem('loginUserTenant') || '{}');  } catch {   return null;  } }; // In ThemeService applyTenantTheme(): void {  const loginUserTenant = LOGGED_USER_TENANT(); // reads at call time } ``` Now it reads localStorage at the moment it's called — not at import time. Fresh data every time, zero service injection needed, fully reusable. Rule of thumb: Never derive auth/session state into module-level constants. If the data depends on a login flow, it won't be ready when Angular bootstraps — always read it lazily. The difference between a constant and a function saved hours of head-scratching. Have you been caught by eager evaluation before? Share it in the comments #Angular #JavaScript #TypeScript #WebDevelopment #FrontendDevelopment #DebuggingTips #TipOfTheDay

I have faced many times this kind of issue and sometimes I ignore it but keep an eye on it to catch it further.

To view or add a comment, sign in

Explore content categories