fix(pets): stop active-pet selection reverting on every page reload

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.
This commit is contained in:
admin committed 2026-08-16 17:17:25 +02:00
1 parent 27cb34df27
commit bc731ac434
1 file changed
+14 -8
+14 -8
View File
@@ -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<ActivePetContextType | null>(null);
const STORAGE_KEY = "active_pet_id";
export function ActivePetProvider({ children }: { children: React.ReactNode }) {
const [activePetId, setActivePetId] = useState<string | null>(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<string | null>(() => {
if (typeof window === "undefined") return null;
return localStorage.getItem(STORAGE_KEY);
});
const setActivePet = (id: string) => {
setActivePetId(id);