From b196c19818135ec375cf35e4713730ee44a13ec8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Oliver=20=C3=98rjavik?= Date: Mon, 16 Nov 2026 19:14:02 +0100 Subject: [PATCH 1/2] feat(recipe): refresh stale data when returning to a long-open page Recipe reads were cached for 30 s, but a page left open never refreshed. useRecipeQuery now refetches when the window regains focus or the tab becomes visible, if the shown data is older than RECIPE_FRESHNESS_MS (30 s). It reuses the background-refresh path, so the grid stays visible, and the recipe editor opts out (refreshWhenStale: false) so typed input is never replaced. Closes #107 --- .../src/features/recipes/RecipeCreatePage.tsx | 5 ++- .../src/features/recipes/recipeQueryCache.ts | 15 +++++-- .../features/recipes/useRecipeQuery.test.tsx | 36 +++++++++++++++ .../src/features/recipes/useRecipeQuery.ts | 45 +++++++++++++++++-- 4 files changed, 94 insertions(+), 7 deletions(-) diff --git a/apps/web/src/features/recipes/RecipeCreatePage.tsx b/apps/web/src/features/recipes/RecipeCreatePage.tsx index 625399f..7a0de32 100644 --- a/apps/web/src/features/recipes/RecipeCreatePage.tsx +++ b/apps/web/src/features/recipes/RecipeCreatePage.tsx @@ -870,7 +870,10 @@ function RecipeEditPage({ id }: { id: string }) { (signal: AbortSignal) => getRecipe(id, signal), [id], ); - const query = useRecipeQuery(id, load, { refreshOnMutation: false }); + const query = useRecipeQuery(id, load, { + refreshOnMutation: false, + refreshWhenStale: false, + }); if (query.loading || query.error) return ; if (!query.data) diff --git a/apps/web/src/features/recipes/recipeQueryCache.ts b/apps/web/src/features/recipes/recipeQueryCache.ts index c104012..19124ce 100644 --- a/apps/web/src/features/recipes/recipeQueryCache.ts +++ b/apps/web/src/features/recipes/recipeQueryCache.ts @@ -1,4 +1,6 @@ -const TTL_MS = 30_000; +/** How long fetched recipe data counts as fresh (cache and refresh-on-focus). */ +export const RECIPE_FRESHNESS_MS = 30_000; +const TTL_MS = RECIPE_FRESHNESS_MS; const MAX_ENTRIES = 40; const entries = new Map(); let generation = 0; @@ -8,18 +10,25 @@ export function clearRecipeQueryCache() { generation += 1; } +/** Drops one entry so the next read fetches from the API. */ +export function forgetRecipeCache(key: string) { + entries.delete(key); +} + export function recipeCacheGeneration() { return generation; } -export function readRecipeCache(key: string): { data: T } | undefined { +export function readRecipeCache( + key: string, +): { data: T; fetchedAt: number } | undefined { const entry = entries.get(key); if (!entry) return; if (entry.expires <= Date.now()) { entries.delete(key); return; } - return { data: entry.data as T }; + return { data: entry.data as T, fetchedAt: entry.expires - TTL_MS }; } export function writeRecipeCache(key: string, data: unknown, started: number) { diff --git a/apps/web/src/features/recipes/useRecipeQuery.test.tsx b/apps/web/src/features/recipes/useRecipeQuery.test.tsx index c84e700..2804aca 100644 --- a/apps/web/src/features/recipes/useRecipeQuery.test.tsx +++ b/apps/web/src/features/recipes/useRecipeQuery.test.tsx @@ -136,3 +136,39 @@ it('invalidates cached pages after a mutation while they are unmounted', async ( await waitFor(() => expect(second.result.current.data).toBe('after')); expect(load).toHaveBeenCalledTimes(2); }); +it('refreshes stale data in the background when the page regains focus', async () => { + const now = vi.spyOn(Date, 'now'); + now.mockReturnValue(1_000_000); + const load = vi + .fn<(_: AbortSignal) => Promise>() + .mockResolvedValueOnce('first') + .mockResolvedValueOnce('fresh'); + const { result } = renderHook(() => useRecipeQuery('freshness', load)); + await waitFor(() => expect(result.current.data).toBe('first')); + + // Returning after 10 s: still fresh, no request. + now.mockReturnValue(1_010_000); + act(() => window.dispatchEvent(new Event('focus'))); + expect(load).toHaveBeenCalledTimes(1); + + // After 31 s the data is stale: refetch, keeping the old data meanwhile. + now.mockReturnValue(1_031_000); + act(() => window.dispatchEvent(new Event('focus'))); + expect(result.current.data).toBe('first'); + await waitFor(() => expect(result.current.data).toBe('fresh')); + expect(load).toHaveBeenCalledTimes(2); + now.mockRestore(); +}); +it('never refreshes on focus when refreshWhenStale is off (forms)', async () => { + const now = vi.spyOn(Date, 'now'); + now.mockReturnValue(2_000_000); + const load = vi.fn(async () => 'form data'); + const { result } = renderHook(() => + useRecipeQuery('editor', load, { refreshWhenStale: false }), + ); + await waitFor(() => expect(result.current.data).toBe('form data')); + now.mockReturnValue(2_100_000); + act(() => window.dispatchEvent(new Event('focus'))); + expect(load).toHaveBeenCalledTimes(1); + now.mockRestore(); +}); diff --git a/apps/web/src/features/recipes/useRecipeQuery.ts b/apps/web/src/features/recipes/useRecipeQuery.ts index 8ab3553..a224dd4 100644 --- a/apps/web/src/features/recipes/useRecipeQuery.ts +++ b/apps/web/src/features/recipes/useRecipeQuery.ts @@ -1,4 +1,4 @@ -import { useEffect, useState } from 'react'; +import { useEffect, useRef, useState } from 'react'; import { useAppStore } from '../../store'; import { recipeErrorMessage, useRecipeChanges } from './recipeApi'; import { @@ -6,6 +6,8 @@ import { writeRecipeCache, recipeCacheGeneration, clearRecipeQueryCache, + forgetRecipeCache, + RECIPE_FRESHNESS_MS, } from './recipeQueryCache'; useAppStore.subscribe((state, previous) => { @@ -23,7 +25,12 @@ useRecipeChanges.subscribe((state, previous) => { export function useRecipeQuery( key: string, load: (signal: AbortSignal) => Promise, - { refreshOnMutation = true } = {}, + { + refreshOnMutation = true, + // Refetch stale data when the user comes back to a long-open page. + // Off for forms (the editor), which must never replace typed input. + refreshWhenStale = true, + } = {}, ) { const userId = useAppStore((state) => state.currentUser?.id); const sessionStatus = useAppStore((state) => state.sessionStatus); @@ -31,8 +38,16 @@ export function useRecipeQuery( refreshOnMutation ? state.revision : 0, ); const [attempt, setAttempt] = useState(0); + // Bumped when the page regains focus with stale data (see below). + const [freshnessCheck, setFreshnessCheck] = useState(0); + const fetchedAt = useRef(0); const identity = JSON.stringify([key, userId]); - const requestKey = JSON.stringify([identity, revision, attempt]); + const requestKey = JSON.stringify([ + identity, + revision, + attempt, + freshnessCheck, + ]); const waiting = sessionStatus === 'restoring'; const [state, setState] = useState<{ identity: string; @@ -53,6 +68,7 @@ export function useRecipeQuery( (data) => { if (!controller.signal.aborted) { if (!cached) writeRecipeCache(identity, data, generation); + fetchedAt.current = cached ? cached.fetchedAt : Date.now(); setState({ identity, key: requestKey, hasData: true, data }); } }, @@ -70,6 +86,29 @@ export function useRecipeQuery( }, [identity, requestKey, load, waiting, attempt]); const current = !waiting && state.identity === identity ? state : undefined; const hasData = current?.hasData ?? false; + + /* + * A page left open (e.g. in a background tab) is refreshed when the user + * returns to it, if its data is older than RECIPE_FRESHNESS_MS. The + * refresh runs in the background: the shown data stays until new data + * arrives (`refreshing`), and failures appear as `refreshError`. + */ + useEffect(() => { + if (!refreshWhenStale || !hasData) return; + function refreshIfStale() { + if (document.visibilityState === 'hidden') return; + if (Date.now() - fetchedAt.current < RECIPE_FRESHNESS_MS) return; + forgetRecipeCache(identity); + fetchedAt.current = Date.now(); // Avoid repeats while it loads. + setFreshnessCheck((value) => value + 1); + } + window.addEventListener('focus', refreshIfStale); + document.addEventListener('visibilitychange', refreshIfStale); + return () => { + window.removeEventListener('focus', refreshIfStale); + document.removeEventListener('visibilitychange', refreshIfStale); + }; + }, [refreshWhenStale, hasData, identity]); return { data: hasData ? current?.data : undefined, error: !hasData && current?.key === requestKey ? current.error : undefined, From ca7b45e67892622664cf95e30379069d619d580b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Oliver=20=C3=98rjavik?= Date: Tue, 17 Nov 2026 00:45:58 +0100 Subject: [PATCH 2/2] fix(recipe): only mark data fresh after a successful refresh fetchedAt was set when a background refresh started, so a failed refresh left old data marked fresh for another 30 seconds. It is now only set when a request succeeds, and a separate in-flight flag stops focus and visibilitychange from starting the same refresh twice. Test: failed refresh, then focus again, retries immediately. --- .../features/recipes/useRecipeQuery.test.tsx | 41 +++++++++++++++++++ .../src/features/recipes/useRecipeQuery.ts | 24 +++++++---- 2 files changed, 57 insertions(+), 8 deletions(-) diff --git a/apps/web/src/features/recipes/useRecipeQuery.test.tsx b/apps/web/src/features/recipes/useRecipeQuery.test.tsx index 2804aca..7b5b0cb 100644 --- a/apps/web/src/features/recipes/useRecipeQuery.test.tsx +++ b/apps/web/src/features/recipes/useRecipeQuery.test.tsx @@ -172,3 +172,44 @@ it('never refreshes on focus when refreshWhenStale is off (forms)', async () => expect(load).toHaveBeenCalledTimes(1); now.mockRestore(); }); +it('retries a failed background refresh the next time the page regains focus', async () => { + const now = vi.spyOn(Date, 'now'); + now.mockReturnValue(3_000_000); + let fail!: (error: Error) => void; + const load = vi + .fn<(_: AbortSignal) => Promise>() + .mockResolvedValueOnce('first') + .mockImplementationOnce( + () => + new Promise((_resolve, reject) => { + fail = reject; + }), + ) + .mockResolvedValueOnce('fresh'); + const { result } = renderHook(() => useRecipeQuery('retry-stale', load)); + await waitFor(() => expect(result.current.data).toBe('first')); + + // Stale: one refresh starts. focus and visibilitychange often fire + // together; the second event must not start another request. + now.mockReturnValue(3_031_000); + act(() => { + window.dispatchEvent(new Event('focus')); + document.dispatchEvent(new Event('visibilitychange')); + }); + expect(load).toHaveBeenCalledTimes(2); + act(() => window.dispatchEvent(new Event('focus'))); + expect(load).toHaveBeenCalledTimes(2); + + // The refresh fails: old data stays, the failure is reported. + await act(async () => fail(new Error('offline'))); + await waitFor(() => expect(result.current.refreshError).toBeTruthy()); + expect(result.current.data).toBe('first'); + + // Returning again shortly after still counts as stale and retries. + now.mockReturnValue(3_032_000); + act(() => window.dispatchEvent(new Event('focus'))); + expect(load).toHaveBeenCalledTimes(3); + await waitFor(() => expect(result.current.data).toBe('fresh')); + expect(result.current.refreshError).toBeUndefined(); + now.mockRestore(); +}); diff --git a/apps/web/src/features/recipes/useRecipeQuery.ts b/apps/web/src/features/recipes/useRecipeQuery.ts index a224dd4..b99c671 100644 --- a/apps/web/src/features/recipes/useRecipeQuery.ts +++ b/apps/web/src/features/recipes/useRecipeQuery.ts @@ -40,7 +40,12 @@ export function useRecipeQuery( const [attempt, setAttempt] = useState(0); // Bumped when the page regains focus with stale data (see below). const [freshnessCheck, setFreshnessCheck] = useState(0); + // When the shown data was fetched. Only set when a request succeeds, so a + // failed refresh leaves the data stale and the next return retries it. const fetchedAt = useRef(0); + // True from a freshness refresh until its request settles, so focus and + // visibilitychange (often fired together) do not start it twice. + const refreshInFlight = useRef(false); const identity = JSON.stringify([key, userId]); const requestKey = JSON.stringify([ identity, @@ -69,17 +74,19 @@ export function useRecipeQuery( if (!controller.signal.aborted) { if (!cached) writeRecipeCache(identity, data, generation); fetchedAt.current = cached ? cached.fetchedAt : Date.now(); + refreshInFlight.current = false; setState({ identity, key: requestKey, hasData: true, data }); } }, (error: unknown) => { - if (!controller.signal.aborted) - setState((previous) => ({ - ...(previous.identity === identity ? previous : { hasData: false }), - identity, - key: requestKey, - error: recipeErrorMessage(error), - })); + if (controller.signal.aborted) return; + refreshInFlight.current = false; + setState((previous) => ({ + ...(previous.identity === identity ? previous : { hasData: false }), + identity, + key: requestKey, + error: recipeErrorMessage(error), + })); }, ); return () => controller.abort(); @@ -97,9 +104,10 @@ export function useRecipeQuery( if (!refreshWhenStale || !hasData) return; function refreshIfStale() { if (document.visibilityState === 'hidden') return; + if (refreshInFlight.current) return; if (Date.now() - fetchedAt.current < RECIPE_FRESHNESS_MS) return; forgetRecipeCache(identity); - fetchedAt.current = Date.now(); // Avoid repeats while it loads. + refreshInFlight.current = true; setFreshnessCheck((value) => value + 1); } window.addEventListener('focus', refreshIfStale);