From bc731ac434116dcac338909868a7a8101ed20eb8 Mon Sep 17 00:00:00 2001 From: neodk2004 Date: Sun, 16 Aug 2026 17:17:25 +0200 Subject: [PATCH] fix(pets): stop active-pet selection reverting on every page reload MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ActivePetProvider read localStorage in a useEffect, but ActivePetInitializer (a descendant, so its effect fires first — React runs effects child-before-parent) checked activePetId in its own effect and overwrote localStorage with the owner's first pet whenever it still saw the initial null — which was always, on every reload, since the provider's own effect hadn't run yet. The switched-to pet never had a chance to be read back. Reads localStorage synchronously via a lazy useState initializer (window-guarded for SSR) instead, so activePetId is already correct on the client's first render and the race can't happen. --- src/context/ActivePetContext.tsx | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/src/context/ActivePetContext.tsx b/src/context/ActivePetContext.tsx index eed9bee..c15ab26 100644 --- a/src/context/ActivePetContext.tsx +++ b/src/context/ActivePetContext.tsx @@ -1,6 +1,6 @@ "use client"; -import { createContext, useContext, useState, useEffect } from "react"; +import { createContext, useContext, useState } from "react"; /** * Active Pet Context — tracks the currently active pet for the logged-in owner. @@ -25,13 +25,19 @@ const ActivePetContext = createContext(null); const STORAGE_KEY = "active_pet_id"; export function ActivePetProvider({ children }: { children: React.ReactNode }) { - const [activePetId, setActivePetId] = useState(null); - - useEffect(() => { - // Initialize from localStorage on client mount (avoids SSR mismatch) - const stored = localStorage.getItem(STORAGE_KEY); - if (stored) setActivePetId(stored); - }, []); + // Lazy initializer reads localStorage synchronously on the client's first + // render (guarded by the window check for SSR, where localStorage doesn't + // exist) instead of via a useEffect. This used to be an effect, but + // ActivePetInitializer's own effect (a descendant, so it fires first — + // React runs effects child-before-parent) raced it: on every reload it + // saw activePetId still at its initial null and overwrote localStorage + // with the owner's first pet before this provider's effect ever read the + // real stored value, silently reverting the active-pet switch on every + // page reload. Reading synchronously here removes the race entirely. + const [activePetId, setActivePetId] = useState(() => { + if (typeof window === "undefined") return null; + return localStorage.getItem(STORAGE_KEY); + }); const setActivePet = (id: string) => { setActivePetId(id);