Skip to content

armgit / lyftr

Public Imported from GitHub
0

Self-hosted fitness tracker. Log workouts, track nutrition, and monitor progress. Docker deployment, mobile-friendly.

Mobile: a failed load says it failed, scoped to what failed (#180)

Carteraae7384e01ce
diff --git a/mobile/app/(tabs)/index.tsx b/mobile/app/(tabs)/index.tsx
index f9c2e7e..a07f6a8 100644
--- a/mobile/app/(tabs)/index.tsx
+++ b/mobile/app/(tabs)/index.tsx
@@ -1,4 +1,4 @@
-import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
+import { useCallback, useEffect, useRef, useState } from 'react'
import { Pressable, RefreshControl, ScrollView, Text, View } from 'react-native'
import { router, useFocusEffect } from 'expo-router'
import { LinearGradient } from 'expo-linear-gradient'
@@ -9,8 +9,8 @@ import {
import {
Activity, ArrowRight, BookOpen, ChevronRight, Dumbbell, Play, Plus, Scale, Timer, TrendingUp,
} from 'lucide-react-native'
-import { apiErrorMessage, activeSessionExercisesForDay, dayLabel, displayVolume, displayWeight, sessionNameForDay, weightShort, type DailyStats, type Program, type WeightLog, type WeightStats, type Workout, workoutDay, entryDay, nextStartableDay, muscleRoast, muscleHex, calcVolume, greeting, formatDay } from '@lyftr/shared'
-import { Alert, AppText, Card, IconButton, Label, Screen, SectionHeader, SegmentedControl } from '../../src/components/ui'
+import { apiErrorMessage, isDailyStats, activeSessionExercisesForDay, dayLabel, displayVolume, displayWeight, sessionNameForDay, weightShort, type DailyStats, type Program, type WeightLog, type WeightStats, type Workout, workoutDay, entryDay, nextStartableDay, muscleRoast, muscleHex, calcVolume, greeting, formatDay } from '@lyftr/shared'
+import { AppText, Card, ErrorState, IconButton, Label, Screen, SectionHeader, SegmentedControl } from '../../src/components/ui'
import { ExerciseImage } from '../../src/components/workouts/ExerciseImage'
import {
MuscleDonut, MuscleSparkline, VolumeBarChart, WeightSparkline,
@@ -65,7 +65,10 @@ function LinkRow({ label, onPress }: { label: string; onPress: () => void }) {
}
export default function Dashboard() {
- const now = useMemo(() => new Date(), [])
+ // Re-read on every load rather than once at mount: this tab stays mounted for the
+ // life of the process, so an app left open overnight kept yesterday's header, week
+ // boundary and "today" dot while load() fetched the real today's food.
+ const [now, setNow] = useState(() => new Date())
const session = useWorkoutSession((s) => s.session)
const startSession = useWorkoutSession((s) => s.startSession)
const user = useAuthStore((s) => s.user)
@@ -93,6 +96,15 @@ export default function Dashboard() {
const [weightStats, setWeightStats] = useState<WeightStats | null>(null)
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
+ // The secondary reads are caught so one dead endpoint cannot blank a working dashboard.
+ // What they must not do is then say nothing: a failed /food/stats rendered today as
+ // 0 kcal, which is what "hasn't eaten yet" looks like. Name -> what the server said,
+ // so the card that never loaded can say why.
+ const [missing, setMissing] = useState<Record<string, string>>({})
+ const foodMissing = "today's food" in missing
+ const weightMissing = 'your weight' in missing
+ const programsMissing = 'your programs' in missing
+
const [sheetOpen, setSheetOpen] = useState(false)
const [volumePeriod, setVolumePeriod] = useState<'7' | '14' | '30'>('7')
const [chartWidth, setChartWidth] = useState(0)
@@ -100,24 +112,45 @@ export default function Dashboard() {
const [heatSel, setHeatSel] = useState<{ day: Date; count: number } | null>(null)
const load = useCallback(async () => {
+ setNow(new Date())
+ // A 200 that is not a list is not an empty list. Unchecked, a half-deployed backend
+ // or a proxy in front of the wrong service rendered "No workouts logged yet" and
+ // "Log your first weight" — the empty-account screen, from a reply we could not read.
+ const rows = <T,>(v: T[] | null | undefined): T[] => {
+ if (!Array.isArray(v)) throw new Error('unreadable')
+ return v
+ }
+ const absent: Record<string, string> = {}
+ const note = (what: string, err: unknown) => {
+ absent[what] = apiErrorMessage(err, "The server didn't say what went wrong.")
+ }
const [ws, ps, fs, wl, wst] = await Promise.all([
- client.workoutAPI.list({ limit: 84 }).catch(() => [] as Workout[]),
- client.programAPI.list({ limit: 100 }).catch(() => [] as Program[]), // backend's max — Up Next must see every program
- client.foodAPI.stats(format(new Date(), 'yyyy-MM-dd')).catch(() => DEFAULT_FOOD),
- client.weightAPI.list({ limit: 14 }).catch(() => [] as WeightLog[]),
- client.weightAPI.stats().catch(() => null),
+ // Uncaught on purpose, mirroring web: this is the primary request, and it is
+ // what lets a total outage reject load() and reach the ErrorState below. With
+ // all five caught, load() could never fail, so the error screen was
+ // unreachable and an outage rendered every tile at 0, silently.
+ client.workoutAPI.list({ limit: 84 }).then(rows),
+ client.programAPI.list({ limit: 100 }).then(rows).catch((err) => { note('your programs', err); return [] as Program[] }), // backend's max — Up Next must see every program
+ client.foodAPI.stats(format(new Date(), 'yyyy-MM-dd')) // the real today, as load() re-reads it
+ // A 200 carrying the wrong shape never reaches the catch; unchecked, the missing
+ // field goes through Math.round and the card reads "NaN".
+ .then((fs) => (isDailyStats(fs) ? fs : Promise.reject(new Error('unreadable'))))
+ .catch((err) => { note("today's food", err); return DEFAULT_FOOD }),
+ client.weightAPI.list({ limit: 14 }).then(rows).catch((err) => { note('your weight', err); return [] as WeightLog[] }),
+ client.weightAPI.stats().catch((err) => { note('your weight', err); return null }),
])
- setWorkouts(ws || [])
- setPrograms(ps || [])
+ setWorkouts(ws)
+ setPrograms(ps)
setFood(fs || DEFAULT_FOOD)
- setWeightLogs(wl || [])
+ setWeightLogs(wl)
setWeightStats(wst)
+ setMissing(absent)
}, [])
useEffect(() => {
fetchSettings()
load()
- .catch((err) => setError(apiErrorMessage(err, 'Failed to load')))
+ .catch((err) => setError(apiErrorMessage(err, "The server didn't say what went wrong.")))
.finally(() => setLoading(false))
}, [fetchSettings, load])
@@ -126,25 +159,40 @@ export default function Dashboard() {
useFocusEffect(
useCallback(() => {
if (!focusedOnce.current) { focusedOnce.current = true; return }
- load()
+ // A failed refocus refetch keeps the stale-but-real data already on screen;
+ // replacing a populated dashboard with an error over a background refresh
+ // would be the louder wrong. The catch exists because load() can reject now.
+ load().catch(() => {})
}, [load])
)
const [refreshing, setRefreshing] = useState(false)
const onRefresh = useCallback(async () => {
setRefreshing(true)
- await load()
+ // Same shape as the refocus refetch: pull-to-refresh over live data keeps the
+ // data on a failure; the spinner stopping with nothing changed is the signal.
+ await load().catch(() => {})
setRefreshing(false)
}, [load])
if (loading) return <DashboardSkeleton />
if (error) {
+ // Every tile here is another request's answer, so a failed load has no honest
+ // partial view — the cards would all read 0, which says "you did nothing this
+ // week" rather than "we could not ask".
return (
<Screen>
- <View className="py-4">
- <Alert variant="error" size="compact">{error}</Alert>
- </View>
+ <ErrorState
+ size="page"
+ title="Couldn't load your dashboard"
+ message={error}
+ onRetry={() => {
+ setError(null)
+ setLoading(true)
+ load().catch((err) => setError(apiErrorMessage(err, "The server didn't say what went wrong."))).finally(() => setLoading(false))
+ }}
+ />
</Screen>
)
}
@@ -332,6 +380,13 @@ export default function Dashboard() {
onPress={startUpNext}
/>
</Card>
+ ) : !session && programsMissing ? (
+ // Programs failed, so there is no "up next" to work out — and with nothing
+ // here the screen reads as an account with no routine, which is a claim we
+ // cannot make from a request that never answered.
+ <Card>
+ <ErrorState title="Couldn't load your programs" message={missing['your programs']} onRetry={onRefresh} />
+ </Card>
) : null}
{/* ── This Week (sessions + current-week dots) ── */}
@@ -569,6 +624,10 @@ export default function Dashboard() {
<Card>
{/* Web links "Log →" to /food; hidden on mobile until a Food page exists. */}
<AppText variant="subheading" className="mb-3">Today's Nutrition</AppText>
+ {foodMissing ? (
+ <ErrorState title="Couldn't load today's food" message={missing["today's food"]} onRetry={onRefresh} />
+ ) : (
+ <>
<View className="mb-3 flex-row items-baseline gap-1.5">
<Text className="font-display-heavy text-tx-primary" style={{ fontSize: 34, lineHeight: 38, fontVariant: ['tabular-nums'] }}>{Math.round(food.total_calories)}</Text>
<AppText variant="caption" color="muted">/ {settings.calorie_target} kcal</AppText>
@@ -593,6 +652,8 @@ export default function Dashboard() {
</View>
))}
</View>
+ </>
+ )}
</Card>
{/* ── Weight quick-log ── */}
@@ -603,7 +664,10 @@ export default function Dashboard() {
right={<LinkRow label="View" onPress={() => router.navigate('/weight')} />}
className="mb-2"
/>
- {weightLogs.length === 0 ? (
+ {weightLogs.length === 0 && weightMissing ? (
+ // Not the "log your first weight" prompt: this reader may have years of them.
+ <ErrorState title="Couldn't load your weight" message={missing['your weight']} onRetry={onRefresh} />
+ ) : weightLogs.length === 0 ? (
<Pressable
onPress={() => { hSelect(); setSheetOpen(true) }}
className="flex-row items-center gap-3 rounded-2xl border border-dashed border-brand-500/30 bg-brand-500/5 p-3.5 active:scale-[0.99]"
@@ -625,7 +689,10 @@ export default function Dashboard() {
</View>
<View className="flex-row items-center gap-2">
{(() => {
- const delta = weightStats?.change_7d ?? 0
+ // No stats is not "no change": say nothing rather than a trend we
+ // never got — and a null or absent delta is no stats at all, not 0.
+ const delta = weightStats?.change_7d
+ if (typeof delta !== 'number' || !Number.isFinite(delta)) return null
if (delta === 0) return <AppText variant="caption" color="muted">7d · no change</AppText>
return (
<Text className="text-xs" style={{ color: delta < 0 ? brand.successSoft : brand.errorSoft, fontVariant: ['tabular-nums'] }}>
@@ -665,7 +732,10 @@ export default function Dashboard() {
new Date(b.logged_at).getTime() - new Date(a.logged_at).getTime()
)
)
- client.weightAPI.stats().then(setWeightStats).catch(() => {})
+ // Dropping the stats rather than keeping them: the entry just logged is in
+ // them, so a failed refetch leaves a 7d trend that is wrong, not merely old.
+ // The delta hides itself when they are absent.
+ client.weightAPI.stats().then(setWeightStats).catch(() => setWeightStats(null))
}}
/>
</Screen>
diff --git a/mobile/app/(tabs)/nutrition/[id].tsx b/mobile/app/(tabs)/nutrition/[id].tsx
index fffa865..706163e 100644
--- a/mobile/app/(tabs)/nutrition/[id].tsx
+++ b/mobile/app/(tabs)/nutrition/[id].tsx
@@ -2,9 +2,9 @@ import { useEffect, useState } from 'react'
import { Image, Pressable, ScrollView, View } from 'react-native'
import { router, useLocalSearchParams } from 'expo-router'
import { ArrowLeft, Edit2, Flame, Trash2 } from 'lucide-react-native'
-import { useAsyncAction, entryDay, type FoodLog, formatDay } from '@lyftr/shared'
-import { Alert,
- AppText, Card, ConfirmSheet, Loading, Screen, deleteConfirmProps,
+import { apiErrorMessage, isNotFound, useAsyncAction, entryDay, type FoodLog, formatDay } from '@lyftr/shared'
+import {
+ AppText, Button, Card, ConfirmSheet, ErrorState, Loading, Screen, deleteConfirmProps,
} from '../../../src/components/ui'
import {
MACRO_COLORS, MACRO_TEXT, MEAL_COLORS, MEAL_ICONS, MEAL_LABELS, type Meal,
@@ -23,6 +23,8 @@ export default function NutritionDetail() {
const [entry, setEntry] = useState<FoodLog | null>(null)
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
+ const [gone, setGone] = useState(false)
+ const [retryKey, setRetryKey] = useState(0)
const [confirming, setConfirming] = useState(false)
const goBack = () => (router.canGoBack() ? router.back() : router.replace('/nutrition'))
@@ -30,9 +32,12 @@ export default function NutritionDetail() {
useEffect(() => {
client.foodAPI.get(Number(id))
.then(setEntry)
- .catch(() => setError('Failed to load entry'))
+ .catch((err) => {
+ setGone(isNotFound(err))
+ setError(apiErrorMessage(err, "The server didn't say what went wrong."))
+ })
.finally(() => setLoading(false))
- }, [id])
+ }, [id, retryKey])
// The catch here just closed up and left the screen unchanged, which is
// indistinguishable from a tap that never registered. It says why now.
@@ -47,12 +52,14 @@ export default function NutritionDetail() {
if (error || !entry) {
return (
<Screen>
- <View className="gap-4 py-4">
- <Pressable onPress={goBack} hitSlop={8} className="flex-row items-center gap-2 self-start active:opacity-60">
- <ArrowLeft size={16} color={colors.txMuted} />
- <AppText variant="body" color="muted">Nutrition</AppText>
- </Pressable>
- <Alert variant="error" size="compact">{error || 'Entry not found'}</Alert>
+ <View className="flex-1 py-4">
+ <ErrorState
+ size="page"
+ title="Couldn't load this entry"
+ message={error ?? 'That entry no longer exists.'}
+ onRetry={error && !gone ? () => { setError(null); setRetryKey((k) => k + 1) } : undefined}
+ secondary={<Button title="Back to nutrition" variant="secondary" onPress={goBack} />}
+ />
</View>
</Screen>
)
diff --git a/mobile/app/(tabs)/nutrition/index.tsx b/mobile/app/(tabs)/nutrition/index.tsx
index 95f0c91..67bfb1e 100644
--- a/mobile/app/(tabs)/nutrition/index.tsx
+++ b/mobile/app/(tabs)/nutrition/index.tsx
@@ -4,11 +4,11 @@ import { router, useFocusEffect, useLocalSearchParams } from 'expo-router'
import * as Haptics from 'expo-haptics'
import { format, subDays, addDays } from 'date-fns'
import {
- AlertCircle, CalendarDays, CheckCircle2, ChevronLeft, ChevronRight, Flame, Plus, Utensils,
+ CalendarDays, CheckCircle2, ChevronLeft, ChevronRight, Flame, Plus, Utensils,
} from 'lucide-react-native'
-import { apiErrorMessage, todayStr, type DailyStats, type FoodLog, dayToLocalDate} from '@lyftr/shared'
+import { apiErrorMessage, isDailyStats, todayStr, type DailyStats, type FoodLog, dayToLocalDate} from '@lyftr/shared'
import {
- AppText, Card, DateInput, IconButton, Label, PageHeader, Screen, SearchField, SectionHeader, SegmentedControl, Toast,
+ AppText, Card, DateInput, ErrorState, IconButton, Label, PageHeader, Screen, SearchField, SectionHeader, SegmentedControl, Skeleton, SkeletonList, StatFailure, Toast,
} from '../../../src/components/ui'
import { MacroRing, MacroHistoryChart, type MacroHistoryPoint } from '../../../src/components/nutrition/NutritionCharts'
import { FoodEntryRow } from '../../../src/components/nutrition/FoodEntryRow'
@@ -51,7 +51,7 @@ const mealForNow = (): Meal => {
}
export default function Nutrition() {
- const { colors, brand, accent, isDark } = useTheme()
+ const { colors, brand, accent } = useTheme()
const { width: windowWidth } = useWindowDimensions()
const settings = useSettingsStore((s) => s.settings)
const fetchSettings = useSettingsStore((s) => s.fetch)
@@ -63,9 +63,17 @@ export default function Nutrition() {
const [logs, setLogs] = useState<FoodLog[]>([])
const [stats, setStats] = useState<DailyStats | null>(null)
const [error, setError] = useState<string | null>(null)
+ // The totals and the history are caught so either can fail without blanking the diary.
+ // Caught is not the same as silent: each keeps what the server said, and the card it
+ // belongs to says so instead of rendering 0 kcal.
+ const [statsError, setStatsError] = useState<string | null>(null)
+ const [historyError, setHistoryError] = useState<string | null>(null)
const [historyPeriod, setHistoryPeriod] = useState<HistoryPeriod>('30d')
const [historyData, setHistoryData] = useState<MacroHistoryPoint[]>([])
+ // The window historyData answers — see the weight trend: a failed switch must not
+ // leave 7d's averages under a 90d heading.
+ const [historyDataPeriod, setHistoryDataPeriod] = useState<HistoryPeriod | null>(null)
const [historyLoading, setHistoryLoading] = useState(false)
const [chartWidth, setChartWidth] = useState(0)
@@ -81,39 +89,75 @@ export default function Nutrition() {
// Reset paging to the first page when the day changes or the query changes.
useEffect(() => { setVisibleCount(FOOD_PAGE) }, [selectedDate, foodQuery])
+ // Which day the logs and totals on screen answer, and whether the day now selected
+ // is still on the wire. Paging days is the same kind of window switch as the trend's
+ // period: yesterday's meals under today's date is not stale data, it is the wrong day.
+ const [loadedDate, setLoadedDate] = useState<string | null>(null)
+ const dayRequest = useRef(0)
+ // The day on screen right now, readable from a callback that was created for an
+ // earlier one (a delete's refetch outliving the day it was fired for).
+ const selectedDateRef = useRef(selectedDate)
+ selectedDateRef.current = selectedDate
+
const loadDay = useCallback(async (date: string) => {
- // Stale-while-revalidate: keep the previous day's logs/stats on screen until the new
- // day's data lands, so paging days doesn't flash the hero/rings/list to empty (the
- // same no-empty-flash behavior the Weight/Programs lists have). Only errors reset.
+ // Last request wins. Without this, paging back three days on a slow connection let
+ // whichever response landed last own the screen, regardless of the day showing.
+ const id = ++dayRequest.current
setError(null)
try {
const defaultStats: DailyStats = {
date, total_calories: 0, total_protein: 0, total_carbs: 0, total_fat: 0, total_fiber: 0, workout_count: 0,
}
+ let statsMessage: string | null = null
const [logData, statsData] = await Promise.all([
- client.foodAPI.list(date),
- client.foodAPI.stats(date).catch(() => defaultStats),
+ // Same rule as the totals beside it: a reply we cannot read is a failure, not a
+ // day with no food in it.
+ client.foodAPI.list(date).then((d) => {
+ if (!Array.isArray(d)) throw new Error('unreadable')
+ return d
+ }),
+ client.foodAPI.stats(date)
+ // A readable 200 is the only kind that counts as data; unchecked, a wrong shape
+ // rendered as 0 kcal, which is what "hasn't eaten yet" looks like.
+ .then((st) => (isDailyStats(st) ? st : Promise.reject(new Error('unreadable'))))
+ .catch((err) => {
+ statsMessage = apiErrorMessage(err, "The server didn't say what went wrong.")
+ return defaultStats
+ }),
])
- setLogs(logData || [])
+ if (id !== dayRequest.current) return
+ setLogs(logData)
setStats(statsData)
+ setStatsError(statsMessage)
+ setLoadedDate(date)
} catch (err: any) {
- setError(apiErrorMessage(err, 'Failed to load food data'))
+ if (id !== dayRequest.current) return
+ setError(apiErrorMessage(err, "The server didn't say what went wrong."))
} finally {
- hasLoadedRef.current = true
+ if (id === dayRequest.current) hasLoadedRef.current = true
}
}, [])
useEffect(() => { loadDay(selectedDate) }, [selectedDate, loadDay])
useEffect(() => { fetchSettings() }, [fetchSettings])
+ // Only the latest request may write: 90d is a slower query than 7d, so a stale wide
+ // answer could otherwise overwrite the narrow one the user just asked for.
+ const historyRequest = useRef(0)
const loadHistory = useCallback(() => {
+ const id = ++historyRequest.current
setHistoryLoading(true)
const days = historyPeriod === '7d' ? 7 : historyPeriod === '30d' ? 30 : 90
return client.foodAPI
.history(days)
- .then((data) => setHistoryData((data as MacroHistoryPoint[]) || []))
- .catch(() => {})
- .finally(() => setHistoryLoading(false))
+ .then((data) => {
+ if (id !== historyRequest.current) return
+ setHistoryData((data as MacroHistoryPoint[]) || [])
+ setHistoryDataPeriod(historyPeriod)
+ setHistoryError(null)
+ })
+ .catch((err) => { if (id === historyRequest.current) setHistoryError(apiErrorMessage(err, "The server didn't say what went wrong.")) })
+ .finally(() => { if (id === historyRequest.current) setHistoryLoading(false) })
}, [historyPeriod])
useEffect(() => { loadHistory() }, [loadHistory])
@@ -148,12 +192,54 @@ export default function Nutrition() {
// Kebab-delete drops the row and refreshes the day's totals (rings + calorie hero).
const onEntryDeleted = useCallback((entryId: number) => {
+ const day = selectedDate
setLogs((prev) => prev.filter((l) => l.id !== entryId))
- client.foodAPI.stats(selectedDate).then(setStats).catch(() => {})
+ // The row is gone from the list either way, so totals that fail to refresh here are
+ // not stale, they are wrong — they still count the entry the reader just deleted.
+ client.foodAPI.stats(selectedDate)
+ .then((st) => {
+ // The reader may have paged to another day while this was in flight; these
+ // totals are not that day's to set, or to declare healthy.
+ if (day !== selectedDateRef.current) return
+ if (!isDailyStats(st)) throw new Error('unreadable')
+ setStats(st)
+ setStatsError(null)
+ })
+ .catch((err) => {
+ if (day !== selectedDateRef.current) return
+ setStatsError(apiErrorMessage(err, "The server didn't say what went wrong."))
+ })
}, [selectedDate])
if (!hasLoadedRef.current) return <NutritionSkeleton />
+ const toastView = toast ? (
+ <Toast variant="success" icon={CheckCircle2} title={toast} onDismiss={() => setToast(null)} />
+ ) : null
+
+ // Rings at 0 kcal and four empty meal sections say "you have eaten nothing today",
+ // which is a different sentence from "we could not ask" — and only one of them is
+ // true. Title stays; the Log Food action does not, since the save it leads to cannot
+ // reach the server either and would outrank the retry.
+ if (error) {
+ return (
+ <Screen>
+ <View className="flex-1 gap-4 pt-4">
+ <PageHeader title="Nutrition" subtitle="Macros & meals" />
+ <ErrorState
+ size="page"
+ title="Couldn't load your food log"
+ message={error}
+ onRetry={() => { void loadDay(selectedDate) }}
+ />
+ </View>
+ {toastView}
+ </Screen>
+ )
+ }
+
+ // The selected day has not been answered yet: not empty, not zero, pending.
+ const dayPending = loadedDate !== selectedDate
const totalCals = stats?.total_calories ?? 0
const calTarget = settings.calorie_target || 2000
const remaining = calTarget - totalCals
@@ -170,10 +256,13 @@ export default function Nutrition() {
const hasMoreFood = visibleCount < filteredEntries.length
const loadMoreFood = () => { if (hasMoreFood) setVisibleCount((c) => c + FOOD_PAGE) }
- // Trends: average daily macros over the loaded history window.
- const histDays = historyData.length
+ // Trends: average daily macros over the loaded history window — only the days that
+ // answer the window now on screen.
+ const historyPoints = historyDataPeriod === historyPeriod ? historyData : []
+ const histDays = historyPoints.length
+ // The average of nothing is not 0 g: with no days loaded the tiles read "—".
const avgMacro = (key: 'protein' | 'carbs' | 'fat') =>
- histDays ? Math.round(historyData.reduce((s, d) => s + (d[key] || 0), 0) / histDays) : 0
+ histDays ? String(Math.round(historyPoints.reduce((s, d) => s + (d[key] || 0), 0) / histDays)) : '—'
const isDiary = view === 'diary'
// Chart width: prefer the measured value, but seed a computed fallback (window − Screen
// px-5 − Card p-4 = 72) so the chart renders immediately on first switch to Trends
@@ -201,7 +290,9 @@ export default function Nutrition() {
return (
<Screen>
<FlatList
- data={isDiary ? visibleEntries : []}
+ // A day still on the wire owns none of these rows: they belong to the day
+ // before it, and rendering them under this date is the same lie as the totals.
+ data={isDiary && !dayPending ? visibleEntries : []}
keyExtractor={(e) => String(e.id)}
showsVerticalScrollIndicator={false}
contentContainerStyle={{ paddingBottom: 32 }}
@@ -236,13 +327,6 @@ export default function Nutrition() {
action={<IconButton icon={Plus} variant="solid" size="md" label="Log Food" onPress={() => openLog(mealForNow())} />}
/>
- {error ? (
- <View className="flex-row items-center gap-2 rounded-xl border border-error-500/20 bg-error-500/10 px-4 py-3">
- <AlertCircle size={18} color={isDark ? brand.errorSoft : brand.error} />
- <AppText variant="body" color="error" className="flex-1">{error}</AppText>
- </View>
- ) : null}
-
{/* Diary (per-day log) vs Trends (multi-day chart) */}
<SegmentedControl options={VIEW_OPTIONS} value={view} onChange={setView} />
@@ -275,7 +359,24 @@ export default function Nutrition() {
</Pressable>
</View>
- {/* Macro summary card */}
+ {/* Macro summary card — the totals are its entire content, so a failed
+ read is stated here rather than as rings at 0, and a day still on the
+ wire is a skeleton rather than the previous day's numbers. */}
+ {dayPending ? (
+ <Card className="gap-4">
+ <Skeleton width={140} height={34} />
+ <Skeleton width="100%" height={10} radius={999} />
+ <View className="flex-row justify-between">
+ <Skeleton width={72} height={72} radius={36} />
+ <Skeleton width={72} height={72} radius={36} />
+ <Skeleton width={72} height={72} radius={36} />
+ </View>
+ </Card>
+ ) : statsError ? (
+ <Card>
+ <ErrorState title="Couldn't load today's totals" message={statsError} onRetry={() => { void loadDay(selectedDate) }} />
+ </Card>
+ ) : (
<Card className="gap-5">
{/* Calorie hero */}
<View className="flex-row items-center justify-between">
@@ -328,6 +429,7 @@ export default function Nutrition() {
</View>
</View>
</Card>
+ )}
</>
) : (
<>
@@ -345,10 +447,14 @@ export default function Nutrition() {
<View style={{ width: 8, height: 8, borderRadius: 2, backgroundColor: color }} />
<Label numberOfLines={1}>{label}</Label>
</View>
- <View className="flex-row items-end gap-1">
- <AppText variant="heading" style={{ fontVariant: ['tabular-nums'] }}>{avgMacro(key)}</AppText>
- <AppText variant="caption" color="muted" className="mb-0.5">g</AppText>
- </View>
+ {histDays === 0 && historyError ? (
+ <StatFailure label={`Couldn't load average ${label.toLowerCase()}`} />
+ ) : (
+ <View className="flex-row items-end gap-1">
+ <AppText variant="heading" style={{ fontVariant: ['tabular-nums'] }}>{avgMacro(key)}</AppText>
+ {histDays ? <AppText variant="caption" color="muted" className="mb-0.5">g</AppText> : null}
+ </View>
+ )}
</Card>
))}
</View>
@@ -366,13 +472,15 @@ export default function Nutrition() {
<View className="h-48 items-center justify-center">
<AppText variant="caption" color="muted">Loading…</AppText>
</View>
- ) : historyData.length === 0 ? (
+ ) : historyPoints.length === 0 && historyError ? (
+ <ErrorState title="Couldn't load your history" message={historyError} onRetry={() => { void loadHistory() }} />
+ ) : historyPoints.length === 0 ? (
<View className="h-48 items-center justify-center gap-2">
<CalendarDays size={32} color={colors.txMuted} style={{ opacity: 0.4 }} />
<AppText variant="caption" color="muted">No data yet — start logging meals</AppText>
</View>
) : (
- <MacroHistoryChart data={historyData} width={chartW} height={220} />
+ <MacroHistoryChart data={historyPoints} width={chartW} height={220} />
)}
</View>
{/* Legend */}
@@ -399,13 +507,13 @@ export default function Nutrition() {
<View className="mt-8 gap-3 pb-3">
<View className="flex-row items-center justify-between px-1">
<Label>{isToday ? "Today's Food" : 'Food'}</Label>
- {dayEntries.length > 0 ? (
+ {dayEntries.length > 0 && !dayPending ? (
<AppText variant="caption" color="muted" style={{ fontVariant: ['tabular-nums'] }}>
{q ? `${filteredEntries.length} of ${dayEntries.length}` : `${dayEntries.length} ${dayEntries.length === 1 ? 'item' : 'items'}`}
</AppText>
) : null}
</View>
- {dayEntries.length > 0 ? (
+ {dayEntries.length > 0 && !dayPending ? (
<SearchField value={foodQuery} onChangeText={setFoodQuery} placeholder="Search this day's food…" />
) : null}
</View>
@@ -413,7 +521,9 @@ export default function Nutrition() {
</View>
}
ListEmptyComponent={
- !isDiary ? null : q ? (
+ !isDiary ? null : dayPending ? (
+ <SkeletonList count={3} />
+ ) : q ? (
<View className="items-center px-4 py-8">
<Utensils size={28} color={colors.txMuted} style={{ opacity: 0.4 }} />
<AppText variant="body" color="muted" className="mt-2">No matches for “{foodQuery.trim()}”</AppText>
@@ -438,9 +548,7 @@ export default function Nutrition() {
/>
{/* Success toast on arrival back from the log flow. */}
- {toast ? (
- <Toast variant="success" icon={CheckCircle2} title={toast} onDismiss={() => setToast(null)} />
- ) : null}
+ {toastView}
</Screen>
)
}
diff --git a/mobile/app/(tabs)/nutrition/log.tsx b/mobile/app/(tabs)/nutrition/log.tsx
index da75849..93dfcc3 100644
--- a/mobile/app/(tabs)/nutrition/log.tsx
+++ b/mobile/app/(tabs)/nutrition/log.tsx
@@ -20,7 +20,7 @@ import {
} from '../../../src/components/nutrition/nutritionMeta'
import { client } from '../../../src/lib/lyftr'
import { useTheme } from '../../../src/theme/useTheme'
-import { entryToResult, findSavedFood, savedToResult, scaleServing } from '@lyftr/shared'
+import { apiErrorMessage, entryToResult, findSavedFood, savedToResult, scaleServing } from '@lyftr/shared'
type Phase = 'search' | 'detail' | 'scan'
type SearchTab = 'recent' | 'myfoods' | 'all'
@@ -113,10 +113,10 @@ export default function LogFood() {
: [...prev, created].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0)))
Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success).catch(() => {})
}
- } catch {
- setFavoriteError(existing
+ } catch (err) {
+ setFavoriteError(apiErrorMessage(err, existing
? `Couldn't remove ${item.name} from Favorites.`
- : `Couldn't add ${item.name} to Favorites.`)
+ : `Couldn't add ${item.name} to Favorites.`))
} finally {
inFlightFavorites.current.delete(key)
setTogglingFavorite(new Set(inFlightFavorites.current))
@@ -126,6 +126,7 @@ export default function LogFood() {
const isToggling = (item: FoodSearchResult) =>
togglingFavorite.has(`${item.name}|${item.brand ?? ''}`)
const [favoriteError, setFavoriteError] = useState<string | null>(null)
+ const [editError, setEditError] = useState<string | null>(null)
const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null)
@@ -142,7 +143,7 @@ export default function LogFood() {
setMeal(entry.meal)
setDate(entryDay(entry))
setPhase('detail')
- }).catch(() => router.replace('/nutrition'))
+ }).catch((err) => setEditError(apiErrorMessage(err, "Couldn't load that entry.")))
}, [editId])
// Recent (today, deduped ≤10) + favourites.
@@ -307,6 +308,15 @@ export default function LogFood() {
above, so a failure has to be visible whichever one the user pressed. Sitting
inside the search phase meant a failed star on the detail screen said nothing
at all and simply snapped back to unfilled. */}
+ {/* An entry we were asked to edit but could not load. This used to replace the
+ route with /nutrition, so a dropped connection silently threw away the edit
+ the user opened. */}
+ {editError ? (
+ <View className="pb-3">
+ <Alert variant="error">{editError}</Alert>
+ </View>
+ ) : null}
+
{favoriteError ? (
<View className="pb-3">
<Alert variant="error">{favoriteError}</Alert>
diff --git a/mobile/app/(tabs)/programs/[id].tsx b/mobile/app/(tabs)/programs/[id].tsx
index 264ef71..3953828 100644
--- a/mobile/app/(tabs)/programs/[id].tsx
+++ b/mobile/app/(tabs)/programs/[id].tsx
@@ -10,7 +10,7 @@ import { useAsyncAction,
activeSessionExercisesForDay, allExercises, apiErrorMessage, dayLabel, displayWeight, sessionNameForDay,
weightShort, type Program, type ProgramSet,
} from '@lyftr/shared'
-import { AppText, ConfirmSheet, Loading, Screen, deleteConfirmProps } from '../../../src/components/ui'
+import { AppText, Button, ConfirmSheet, ErrorState, Loading, Screen, deleteConfirmProps } from '../../../src/components/ui'
import { ExerciseImage } from '../../../src/components/workouts/ExerciseImage'
import { client, useSettingsStore, useWorkoutSession } from '../../../src/lib/lyftr'
import { useTheme } from '../../../src/theme/useTheme'
@@ -76,8 +76,14 @@ export default function ProgramDetail() {
const [program, setProgram] = useState<Program | null>(null)
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
+ // Bumping this re-runs the load effect — three lines, rather than restructuring a
+ // working effect to gain a retry button.
+ const [retryKey, setRetryKey] = useState(0)
const [confirming, setConfirming] = useState(false)
const [resolving, setResolving] = useState(false)
+ // Separate from `error`, which replaces the whole screen: a failed resolve must leave the
+ // program on screen so the same buttons are still under the thumb to retry.
+ const [resolveError, setResolveError] = useState<string | null>(null)
const [showAllSuggestions, setShowAllSuggestions] = useState(false)
const [selectedDayIdx, setSelectedDayIdx] = useState(0)
@@ -101,12 +107,13 @@ export default function ProgramDetail() {
const resolveSuggestions = async (accept: number[], dismiss: number[]) => {
if (!program || resolving) return
setResolving(true)
+ setResolveError(null)
++requestSeq.current
try {
const updated = await client.programAPI.resolveSuggestions(program.id, { accept, dismiss })
setProgram(updated)
- } catch {
- // leave the banner in place so the user can retry
+ } catch (err) {
+ setResolveError(apiErrorMessage(err, "Couldn't save those targets."))
} finally {
// Invalidate any focus refetch still in flight from before this point — its
// response can't be trusted to reflect this write, whichever order it lands in.
@@ -143,14 +150,17 @@ export default function ProgramDetail() {
loadedRef.current = true
}
} catch (err) {
- if (!cancelled && !loadedRef.current) setError(apiErrorMessage(err, 'Failed to load program'))
+ if (!cancelled && !loadedRef.current) setError(apiErrorMessage(err, "The server didn't say what went wrong."))
} finally {
if (!cancelled) setLoading(false)
}
}
load()
return () => { cancelled = true }
- }, [id])
+ // retryKey is not read in the body — it IS the trigger. Changing it gives the
+ // callback a new identity, which is what makes useFocusEffect run the load again.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [id, retryKey])
)
const goBack = () => (router.canGoBack() ? router.back() : router.replace('/programs'))
@@ -180,15 +190,14 @@ export default function ProgramDetail() {
if (error || !program) {
return (
<Screen>
- <View className="gap-4 py-4">
- <Pressable onPress={goBack} hitSlop={8} className="flex-row items-center gap-2 self-start active:opacity-60">
- <ArrowLeft size={16} color={colors.txMuted} />
- <AppText variant="body" color="muted">Back</AppText>
- </Pressable>
- <View className="flex-row items-center gap-2 rounded-xl border border-error-500/20 bg-error-500/10 p-4">
- <AlertCircle size={20} color={isDark ? brand.errorSoft : brand.error} />
- <AppText variant="body" color="error" className="flex-1">{error || 'Program not found'}</AppText>
- </View>
+ <View className="flex-1 py-4">
+ <ErrorState
+ size="page"
+ title="Couldn't load this program"
+ message={error ?? 'That program no longer exists.'}
+ onRetry={error ? () => { setError(null); setRetryKey((k) => k + 1) } : undefined}
+ secondary={<Button title="Back to programs" variant="secondary" onPress={goBack} />}
+ />
</View>
</Screen>
)
@@ -345,6 +354,12 @@ export default function ProgramDetail() {
{showAllSuggestions ? <ChevronUp size={14} color={warningColor} /> : <ChevronDown size={14} color={warningColor} />}
</Pressable>
)}
+ {resolveError && (
+ <View className="flex-row items-start gap-2 px-4 py-2.5 border-t border-surface-border/60">
+ <AlertCircle size={16} color={brand.error} />
+ <AppText variant="caption" color="error" className="flex-1">{resolveError}</AppText>
+ </View>
+ )}
<View className="flex-row gap-2 px-4 py-3 border-t border-surface-border/60">
<Pressable
onPress={() => resolveSuggestions([], suggestedSetIds)}
diff --git a/mobile/app/(tabs)/programs/[id]/edit.tsx b/mobile/app/(tabs)/programs/[id]/edit.tsx
index 1258857..b2d5609 100644
--- a/mobile/app/(tabs)/programs/[id]/edit.tsx
+++ b/mobile/app/(tabs)/programs/[id]/edit.tsx
@@ -3,8 +3,8 @@ import { Platform, ScrollView, View } from 'react-native'
import { router, useLocalSearchParams } from 'expo-router'
import { AlertCircle, ArrowLeft, BookOpen, CalendarDays, FileText } from 'lucide-react-native'
import type { LucideIcon } from 'lucide-react-native'
-import { useAsyncAction, displayToLbs, hasWorkoutExercises, lbsToDisplay, weightShort, type Exercise } from '@lyftr/shared'
-import { AppText, Button, Field, IconButton, Label, Loading, Screen } from '../../../../src/components/ui'
+import { apiErrorMessage, useAsyncAction, displayToLbs, hasWorkoutExercises, lbsToDisplay, weightShort, type Exercise } from '@lyftr/shared'
+import { AppText, Button, ErrorState, Field, IconButton, Label, Loading, Screen } from '../../../../src/components/ui'
import { KeyboardDoneBar } from '../../../../src/components/workouts/KeyboardDoneBar'
import { ProgramDaysEditor } from '../../../../src/components/programs/ProgramDaysEditor'
import { client, useSettingsStore } from '../../../../src/lib/lyftr'
@@ -40,6 +40,10 @@ export default function EditProgram() {
// Only what the FORM can say before anything is sent. What the SERVER says lives
// on `save` below; both render in the same alert.
const [error, setError] = useState('')
+ // Separate from `error`, which is this form's own validation. A load that never
+ // arrived is not a missing field — there is nothing to edit.
+ const [loadError, setLoadError] = useState<string | null>(null)
+ const [retryKey, setRetryKey] = useState(0)
const [pickerExercises, setPickerExercises] = useState<Record<number, Exercise>>({})
const [formData, setFormData] = useState<ProgramFormData>({ name: '', notes: '', days: [] })
const scrollRef = useRef<ScrollView>(null)
@@ -81,11 +85,11 @@ export default function EditProgram() {
})),
})
})
- .catch(() => { if (!cancelled) setError('Failed to load program') })
+ .catch((err) => { if (!cancelled) setLoadError(apiErrorMessage(err, "The server didn't say what went wrong.")) })
.finally(() => { if (!cancelled) setInitialLoading(false) })
return () => { cancelled = true }
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [id])
+ }, [id, retryKey])
const goBack = () => (router.canGoBack() ? router.back() : router.replace('/programs'))
@@ -134,6 +138,20 @@ export default function EditProgram() {
void save.run()
}
+ if (loadError) {
+ return (
+ <Screen>
+ <ErrorState
+ size="page"
+ title="Couldn't load this program"
+ message={loadError}
+ onRetry={() => { setLoadError(null); setRetryKey((k) => k + 1) }}
+ secondary={<Button title="Back to programs" variant="secondary" onPress={goBack} />}
+ />
+ </Screen>
+ )
+ }
+
if (initialLoading) return <Loading />
const totalExercises = formData.days.reduce((s, d) => s + d.exercises.length, 0)
diff --git a/mobile/app/(tabs)/programs/index.tsx b/mobile/app/(tabs)/programs/index.tsx
index 8094b82..1d40d06 100644
--- a/mobile/app/(tabs)/programs/index.tsx
+++ b/mobile/app/(tabs)/programs/index.tsx
@@ -4,7 +4,7 @@ import { router, useFocusEffect } from 'expo-router'
import { BookOpen, Plus } from 'lucide-react-native'
import type { Program } from '@lyftr/shared'
import { programExerciseCount } from '@lyftr/shared'
-import { AppText, Card, EmptyState, IconButton, Label, PageHeader, Screen, SearchField } from '../../../src/components/ui'
+import { AppText, Card, EmptyState, ErrorState, IconButton, Label, PageHeader, Screen, SearchField, StatFailure } from '../../../src/components/ui'
import { ProgramCard } from '../../../src/components/programs/ProgramCard'
import { ProgramsSkeleton } from '../../../src/components/programs/ProgramsSkeleton'
import { useServerInfiniteList } from '../../../src/hooks/useServerInfiniteList'
@@ -29,8 +29,10 @@ export default function Programs() {
client.programAPI.list({ offset, limit, q: debouncedSearch || undefined }),
[debouncedSearch]
)
- const { items: programs, loadMore, hasMore, loading, initialLoading, refreshing, reload } =
- useServerInfiniteList<Program>({ fetcher, deps: [debouncedSearch] })
+ const {
+ items: programs, loadMore, hasMore, loading, initialLoading, refreshing, reload,
+ error: listError, retry: retryList,
+ } = useServerInfiniteList<Program>({ fetcher, deps: [debouncedSearch] })
// The stack keeps this screen mounted under the detail/form screens; refetch on
// re-focus so an edit/delete/create there reflects here. Skip the first focus (the
@@ -46,6 +48,19 @@ export default function Programs() {
}, [reload])
)
+ // Which query the rows on screen answer. Keeping the previous results while a new
+ // search runs is right — until that search fails, at which point the field says one
+ // thing and the rows below it another. Then they are not stale, they are a different
+ // query's answer, and the error takes their place.
+ const [answeredQuery, setAnsweredQuery] = useState('')
+ // Keyed on the hook's own loading flag, which is already true by the time this runs
+ // for a new query — `refreshing` is not, so this marked a query answered before its
+ // request had left, and a failure then kept the previous query's rows on screen.
+ useEffect(() => {
+ if (!loading && listError == null) setAnsweredQuery(debouncedSearch)
+ }, [loading, listError, debouncedSearch])
+ const queryAnswered = listError == null || answeredQuery === debouncedSearch
+
const [pulling, setPulling] = useState(false)
const onPullRefresh = useCallback(async () => {
setPulling(true)
@@ -58,20 +73,40 @@ export default function Programs() {
// the Workouts list.
if (initialLoading) return <ProgramsSkeleton />
+ // Nothing arrived, so there is no screen to draw around the failure: tiles would read 0
+ // and the create button would sit beside a list we cannot show. One error for the page,
+ // under the same title. A later page failing under rows that did arrive is the footer's.
+ // Not while a search is running: taking the whole screen takes the field the query
+ // was typed into, and retry could then only re-run the request that just failed.
+ if (listError && programs.length === 0 && !debouncedSearch) {
+ return (
+ <Screen>
+ <View className="flex-1 gap-5 py-4">
+ <PageHeader title="Programs" subtitle="Reusable workout templates" />
+ <ErrorState size="page" title="Couldn't load your programs" message={listError} onRetry={retryList} retrying={loading} />
+ </View>
+ </Screen>
+ )
+ }
+
// Stale-while-revalidate: dim the loaded content while a search re-fetches (the
// previous results stay on screen until the fresh page lands). Pagination (loadMore)
// is excluded so appending a page doesn't dim the whole list.
const dim = refreshing
+ // Nothing loaded and the read failed: "0+ programs" is true of every account there
+ // has ever been. Reached with a search on screen; otherwise the page error owns this.
+ const countsUnknown = listError != null && (programs.length === 0 || !queryAnswered)
const stats = [
- // 1:1 with web: summarize the *loaded* items, not a server-side stat.
- { label: 'Total', value: String(programs.length), unit: 'programs' },
+ // `programs` is what has loaded, not how many exist: while pages remain it is a lower
+ // bound. A failed page is also "pages remain" — the hook drops hasMore on error.
+ { label: 'Total', value: hasMore || listError != null ? `${programs.length}+` : String(programs.length), unit: 'programs' },
{
label: 'Avg Exercises',
value:
programs.length > 0
? String(Math.round(programs.reduce((s, p) => s + programExerciseCount(p), 0) / programs.length))
- : '0',
+ : '—',
unit: 'per program',
},
]
@@ -79,7 +114,7 @@ export default function Programs() {
return (
<Screen>
<FlatList
- data={programs}
+ data={queryAnswered ? programs : []}
keyExtractor={(p) => String(p.id)}
showsVerticalScrollIndicator={false}
contentContainerStyle={{ paddingBottom: 32 }}
@@ -112,10 +147,14 @@ export default function Programs() {
{stats.map((s) => (
<Card key={s.label} className="flex-1 rounded-2xl">
<Label className="mb-2" numberOfLines={1}>{s.label}</Label>
+ {countsUnknown ? (
+ <StatFailure label={`Couldn't load ${s.label.toLowerCase()}`} />
+ ) : (
<View className="flex-row items-end gap-1">
<AppText variant="heading" style={{ fontVariant: ['tabular-nums'] }}>{s.value}</AppText>
<AppText variant="caption" color="muted" className="mb-0.5" numberOfLines={1}>{s.unit}</AppText>
</View>
+ )}
</Card>
))}
</View>
@@ -138,7 +177,11 @@ export default function Programs() {
</View>
)}
ListEmptyComponent={
- loading ? null : (
+ loading ? null : listError ? (
+ // Reached only with a search on screen; "No programs found" would blame the
+ // query for a request that never landed.
+ <ErrorState title="Couldn't load your programs" message={listError} onRetry={retryList} retrying={loading} />
+ ) : (
<EmptyState
icon={BookOpen}
title="No programs found"
@@ -150,7 +193,9 @@ export default function Programs() {
// Pagination-only spinner: `!dim` keeps it from firing during a full
// (re)load — there the content is already grayed, so a footer spinner
// would read as an unwanted "loading" in the middle.
- hasMore && loading && !dim && programs.length > 0 ? (
+ listError && programs.length > 0 ? (
+ <ErrorState title="Couldn't load your programs" message={listError} onRetry={retryList} retrying={loading} />
+ ) : hasMore && loading && !dim && programs.length > 0 ? (
<View className="items-center py-3">
<ActivityIndicator size="small" color={accent} />
</View>
diff --git a/mobile/app/(tabs)/settings/index.tsx b/mobile/app/(tabs)/settings/index.tsx
index 6fee5b0..b15e3fd 100644
--- a/mobile/app/(tabs)/settings/index.tsx
+++ b/mobile/app/(tabs)/settings/index.tsx
@@ -30,6 +30,7 @@ import {
AppText,
Button,
ConfirmSheet,
+ ErrorState,
Field,
IconButton,
Loading,
@@ -59,6 +60,11 @@ export default function SettingsScreen() {
const settings = useSettingsStore((s) => s.settings)
const loaded = useSettingsStore((s) => s.loaded)
+ // True when `loaded` is standing on defaults because the read failed. Only the
+ // server-backed block is gated on it: theme, layout, rest timer and the backend URL
+ // are device-side, and the URL row is the very control someone needs WHEN the
+ // server cannot be reached.
+ const settingsLoadFailed = useSettingsStore((s) => s.loadFailed)
const fetchSettings = useSettingsStore((s) => s.fetch)
const updateSettings = useSettingsStore((s) => s.update)
const setWorkoutLayout = useSettingsStore((s) => s.setWorkoutLayout)
@@ -122,6 +128,14 @@ export default function SettingsScreen() {
const handleSaveTargets = () => { void saveTargets.run() }
+ // The unit toggle used to call updateSettings() bare, so a failed PUT was a floating
+ // rejection: nothing told the user, and the app kept showing the unit the server had
+ // refused until the next launch quietly flipped it back. The store rolls the value
+ // back now; this is what says why.
+ const changeUnit = useAsyncAction(async (unit: 'lbs' | 'kg') => {
+ await updateSettings({ weight_unit: unit })
+ }, 'Could not change the weight unit')
+
const saveServer = async () => {
setTesting(true)
setServerMsg(null)
@@ -152,6 +166,10 @@ export default function SettingsScreen() {
if (saveTargets.error) setToast({ variant: 'error', title: 'Could not save targets', description: saveTargets.error })
}, [saveTargets.error])
+ useEffect(() => {
+ if (changeUnit.error) setToast({ variant: 'error', title: 'Could not change units', description: changeUnit.error })
+ }, [changeUnit.error])
+
useEffect(() => {
if (deleteAccount.error) {
setConfirmDelete(false)
@@ -292,7 +310,21 @@ export default function SettingsScreen() {
</View>
</SettingsGroup>
- {/* Units & Targets */}
+ {/* Units & Targets — the only server-backed, editable block on this screen.
+
+ Withheld rather than filled with defaults: the store falls back to
+ 2000/150/250/65 so the rest of the app keeps working, and Save would PUT
+ those straight over the user's real targets. */}
+ {settingsLoadFailed ? (
+ <SettingsGroup title="Units & Targets">
+ <ErrorState
+ size="section"
+ title="Couldn't load your goals"
+ message="These are your saved targets and units, so we won't guess at them. Everything else here still works."
+ onRetry={() => { void fetchSettings() }}
+ />
+ </SettingsGroup>
+ ) : (
<SettingsGroup title="Units & Targets" footnote="Weight unit applies instantly across the app. Nutrition targets power the dashboard rings.">
<SettingsRow
icon={Scale}
@@ -300,7 +332,7 @@ export default function SettingsScreen() {
below={
<SegmentedControl
value={settings.weight_unit}
- onChange={(u) => updateSettings({ weight_unit: u })}
+ onChange={(u) => { void changeUnit.run(u) }}
options={[
{ value: 'lbs', label: 'lbs' },
{ value: 'kg', label: 'kg' },
@@ -340,6 +372,7 @@ export default function SettingsScreen() {
<Button title="Save targets" onPress={handleSaveTargets} loading={saveTargets.busy} className="mt-1" />
</View>
</SettingsGroup>
+ )}
{/* Server */}
<SettingsGroup title="Server" footnote="The self-hosted backend this app talks to. Leave the URL blank to use the default.">
diff --git a/mobile/app/(tabs)/weight/[id].tsx b/mobile/app/(tabs)/weight/[id].tsx
index c38923e..7870585 100644
--- a/mobile/app/(tabs)/weight/[id].tsx
+++ b/mobile/app/(tabs)/weight/[id].tsx
@@ -3,9 +3,9 @@ import { Pressable, ScrollView, View } from 'react-native'
import { router, useLocalSearchParams } from 'expo-router'
import * as Haptics from 'expo-haptics'
import { ArrowLeft, Edit2, Scale, Trash2 } from 'lucide-react-native'
-import { useAsyncAction, apiErrorMessage, dayToInstant, displayWeight, maxWeight, resolveWeightLbs, weightError, weightShort, type WeightLog, entryDay, BODYWEIGHT_STEP, clampStep, formatDay } from '@lyftr/shared'
+import { useAsyncAction, apiErrorMessage, isNotFound, dayToInstant, displayWeight, maxWeight, resolveWeightLbs, weightError, weightShort, type WeightLog, entryDay, BODYWEIGHT_STEP, clampStep, formatDay } from '@lyftr/shared'
import { Alert,
- AppText, Button, Card, ConfirmSheet, DateInput, Field, Label, Loading, NumberField,
+ AppText, Button, Card, ConfirmSheet, DateInput, ErrorState, Field, Label, Loading, NumberField,
NumericKeyboardAccessory, NUMERIC_ACCESSORY_ID, Screen, StepperTile, deleteConfirmProps,
} from '../../../src/components/ui'
import { client, useSettingsStore } from '../../../src/lib/lyftr'
@@ -21,6 +21,8 @@ export default function WeightDetail() {
const [log, setLog] = useState<WeightLog | null>(null)
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
+ const [gone, setGone] = useState(false)
+ const [retryKey, setRetryKey] = useState(0)
// Edit mode
const [editing, setEditing] = useState(false)
@@ -44,10 +46,13 @@ export default function WeightDetail() {
// Deep-link from the list kebab's Edit action opens straight into edit mode.
if (edit) setEditing(true)
})
- .catch((err) => setError(apiErrorMessage(err, 'Failed to load entry')))
+ .catch((err) => {
+ setGone(isNotFound(err))
+ setError(apiErrorMessage(err, "The server didn't say what went wrong."))
+ })
.finally(() => setLoading(false))
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [id])
+ }, [id, retryKey])
const startEdit = () => {
if (!log) return
@@ -99,12 +104,14 @@ export default function WeightDetail() {
if (error || !log) {
return (
<Screen>
- <View className="gap-4 py-4">
- <Pressable onPress={goBack} hitSlop={8} className="flex-row items-center gap-2 self-start active:opacity-60">
- <ArrowLeft size={16} color={colors.txMuted} />
- <AppText variant="body" color="muted">Weight</AppText>
- </Pressable>
- <Alert variant="error" size="compact">{error || 'Entry not found'}</Alert>
+ <View className="flex-1 py-4">
+ <ErrorState
+ size="page"
+ title="Couldn't load this entry"
+ message={error ?? 'That entry no longer exists.'}
+ onRetry={error && !gone ? () => { setError(null); setRetryKey((k) => k + 1) } : undefined}
+ secondary={<Button title="Back to weight" variant="secondary" onPress={goBack} />}
+ />
</View>
</Screen>
)
diff --git a/mobile/app/(tabs)/weight/index.tsx b/mobile/app/(tabs)/weight/index.tsx
index 2da3368..da37562 100644
--- a/mobile/app/(tabs)/weight/index.tsx
+++ b/mobile/app/(tabs)/weight/index.tsx
@@ -7,16 +7,17 @@ import {
Activity, ArrowDown, ArrowUp, Calendar, Minus, Scale, Sunrise,
TrendingDown, TrendingUp, X,
} from 'lucide-react-native'
-import { useAsyncAction, apiErrorMessage, dayToInstant, daysAgoStr, displayToLbs, displayWeight, maxWeight, todayStr, weightError, weightShort, type WeightLog, type WeightStats, entryDay, dayToLocalDate, BODYWEIGHT_STEP, clampStep, formatDay } from '@lyftr/shared'
+import { apiErrorMessage, useAsyncAction, dayToInstant, daysAgoStr, displayToLbs, displayWeight, maxWeight, todayStr, weightError, weightShort, type WeightLog, type WeightStats, entryDay, dayToLocalDate, BODYWEIGHT_STEP, clampStep, formatDay } from '@lyftr/shared'
import { Alert,
- AppText, Button, Card, DateInput, Field, Label, NumberField, NumericKeyboardAccessory,
- NUMERIC_ACCESSORY_ID, PageHeader, Screen, SegmentedControl, StepperTile,
+ AppText, BarbellBroken, Button, Card, DateInput, ErrorState, Field, Label, NumberField, NumericKeyboardAccessory,
+ NUMERIC_ACCESSORY_ID, PageHeader, Screen, SegmentedControl, Skeleton, StatFailure, StepperTile,
} from '../../../src/components/ui'
import { ExerciseHistoryChart, type ChartPoint } from '../../../src/components/workouts/ExerciseHistoryChart'
import { WeightEntryRow } from '../../../src/components/weight/WeightEntryRow'
import { WeightSkeleton } from '../../../src/components/weight/WeightSkeleton'
import { useServerInfiniteList } from '../../../src/hooks/useServerInfiniteList'
import { client, useSettingsStore } from '../../../src/lib/lyftr'
+import { semanticInk } from '../../../src/theme/theme'
import { useTheme } from '../../../src/theme/useTheme'
const PERIODS = ['7d', '30d', '90d', 'All'] as const
@@ -29,7 +30,7 @@ export default function Weight() {
const fetchSettings = useSettingsStore((s) => s.fetch)
const unit = settings.weight_unit
const wUnit = weightShort(unit)
- const { colors, accent, brand } = useTheme()
+ const { colors, accent, brand, isDark } = useTheme()
const [period, setPeriod] = useState<Period>('30d')
const [stats, setStats] = useState<WeightStats | null>(null)
@@ -37,21 +38,59 @@ export default function Weight() {
// Paginated history list (newest-first) — the FlatList data.
const fetcher = useCallback((offset: number, limit: number) => client.weightAPI.list({ offset, limit }), [])
- const { items, loadMore, hasMore, loading, initialLoading, reload } =
- useServerInfiniteList<WeightLog>({ fetcher })
+ const {
+ items, loadMore, hasMore, loading, initialLoading, reload,
+ error: listError, retry: retryList,
+ } = useServerInfiniteList<WeightLog>({ fetcher })
// Chart data — a separate period-scoped fetch (uncapped at 1000), re-fetched when the
// period changes and after every successful log.
const [chartLogs, setChartLogs] = useState<WeightLog[]>([])
+ // Which window chartLogs answers. A failed refetch keeps the series on screen, and
+ // that is right when it is the same question asked again — but tapping 90d and
+ // failing would otherwise leave 30d's numbers under a 90d label, which is not stale
+ // data, it is the wrong answer. Kept here so the screen can tell those apart.
+ const [chartPeriod, setChartPeriod] = useState<Period | null>(null)
+ // In flight for the window now selected. Without this the provenance rule above reads
+ // as an answer: the figures went to "—" and the chart to "No data for this period"
+ // while the request for that period was still on the wire.
+ const [chartLoading, setChartLoading] = useState(true)
+
+ // Both reads used to swallow their failure, so the figures below fell back to 0 and
+ // the screen rendered measurements it had never received.
+ const [chartError, setChartError] = useState<string | null>(null)
+ const [statsError, setStatsError] = useState<string | null>(null)
+
+ // Only the latest request may write. A wider window is a slower query, so tapping All
+ // then 7d can land All's answer last, and every figure would then describe a period
+ // the user is not looking at. chartLogs is left alone on failure: a failed refetch
+ // keeps the series already on screen.
+ const chartRequest = useRef(0)
// Returns the fetch promise so pull-to-refresh can await a full refresh.
const refetchChart = useCallback(() => {
+ const id = ++chartRequest.current
+ setChartLoading(true)
const days = PERIOD_DAYS[period]
const from = days != null ? daysAgoStr(days) : undefined
- return client.weightAPI.list({ limit: 1000, from }).then((data) => setChartLogs(data || [])).catch(() => {})
+ return client.weightAPI.list({ limit: 1000, from })
+ .then((data) => {
+ if (id !== chartRequest.current) return
+ setChartLogs(data || [])
+ setChartPeriod(period)
+ setChartError(null)
+ })
+ .catch((err) => { if (id === chartRequest.current) setChartError(apiErrorMessage(err, "Couldn't load your weight trend.")) })
+ .finally(() => { if (id === chartRequest.current) setChartLoading(false) })
}, [period])
useEffect(() => { refetchChart() }, [refetchChart])
- const refetchStats = useCallback(() => client.weightAPI.stats().then(setStats).catch(() => {}), [])
+ const statsRequest = useRef(0)
+ const refetchStats = useCallback(() => {
+ const id = ++statsRequest.current
+ return client.weightAPI.stats()
+ .then((data) => { if (id === statsRequest.current) { setStats(data); setStatsError(null) } })
+ .catch((err) => { if (id === statsRequest.current) setStatsError(apiErrorMessage(err, "Couldn't load your weight stats.")) })
+ }, [])
useEffect(() => {
fetchSettings()
refetchStats()
@@ -64,6 +103,24 @@ export default function Weight() {
[reload, refetchStats, refetchChart]
)
+ // One control puts all three reads back, so nobody has to work out which failed.
+ // retryList, not reload: a failed later page is resumed rather than re-fetched from 0.
+ const [retrying, setRetrying] = useState(false)
+ const [heldPageError, setHeldPageError] = useState<string | null>(null)
+ // What the page-level error is saying right now, readable from retryAll, which runs
+ // before this render's derived values exist.
+ const pageErrorRef = useRef<string | null>(null)
+ const retryAll = () => {
+ if (retrying) return
+ setHeldPageError(pageErrorRef.current)
+ setRetrying(true)
+ retryList()
+ Promise.all([refetchStats(), refetchChart()]).finally(() => {
+ setRetrying(false)
+ setHeldPageError(null)
+ })
+ }
+
// Pull-to-refresh: drive the native RefreshControl spinner off a full refresh.
const [pulling, setPulling] = useState(false)
const onPullRefresh = useCallback(async () => {
@@ -107,11 +164,13 @@ export default function Weight() {
// Oldest → newest for the chart. Weight in the display unit; `sub` feeds the tap bubble.
const chartData: ChartPoint[] = useMemo(
() =>
- [...chartLogs].reverse().map((l) => {
+ // Same provenance rule as the figures: a series fetched for another window is not
+ // this window's trend, however recent it is.
+ (chartPeriod === period ? [...chartLogs] : []).reverse().map((l) => {
const d = dayToLocalDate(entryDay(l))
return { date: format(d, 'M/d'), weight: displayWeight(l.weight, unit), sub: format(d, 'MMM d, yyyy') }
}),
- [chartLogs, unit]
+ [chartLogs, chartPeriod, period, unit]
)
const [chartWidth, setChartWidth] = useState(0)
@@ -154,10 +213,11 @@ export default function Weight() {
// Period stats computed from chartLogs (period-scoped server fetch). For "All" prefer
// the server-computed aggregate since it isn't capped at 1000.
- const periodValues = chartLogs.map((l) => l.weight) // raw lbs from DB, newest first
+ // Values only count for the period they were fetched for.
+ const periodValues = chartPeriod === period ? chartLogs.map((l) => l.weight) : [] // raw lbs, newest first
const useServerAggregate = period === 'All' && stats != null
- const currentLbs = periodValues[0] ?? stats?.latest ?? 0
- const oldestLbs = periodValues[periodValues.length - 1] ?? stats?.starting ?? 0
+ const currentLbs = periodValues[0] ?? stats?.latest ?? items[0]?.weight ?? 0
+ const oldestLbs = periodValues[periodValues.length - 1] ?? stats?.starting ?? currentLbs
const changeLbs = currentLbs - oldestLbs
const avgLbs = useServerAggregate
? stats!.avg ?? 0
@@ -167,6 +227,39 @@ export default function Weight() {
const minLbs = useServerAggregate ? stats!.min ?? 0 : periodValues.length > 0 ? Math.min(...periodValues) : 0
const maxLbs = useServerAggregate ? stats!.max ?? 0 : periodValues.length > 0 ? Math.max(...periodValues) : 0
+ // The window selected has not been answered yet: not empty, not unknown, pending.
+ const chartPending = chartLoading && chartPeriod !== period
+
+ // Scope the error to the scope of the failure: three reads failing because the server
+ // is down is one problem, and gets one error with one retry.
+ const loadFailed = chartError != null || statsError != null || listError != null
+ const everythingFailed = chartError != null && statsError != null && listError != null
+ && items.length === 0 && periodValues.length === 0
+ // Hold the page error across a retry. retryList clears its error the moment it is
+ // called, so without this the screen tore itself down into a half-broken one for as
+ // long as the requests took, then rebuilt the same error.
+ const pageError = everythingFailed
+ ? (listError ?? chartError ?? statsError ?? '')
+ : retrying
+ ? heldPageError
+ : null
+ pageErrorRef.current = pageError
+
+ // A number we never received is not zero, and neither is the average of nothing: with
+ // no values the tiles read "—" on a new account and the failure mark on an outage.
+ const currentKnown = periodValues.length > 0 || stats != null || items.length > 0
+ const changeKnown = periodValues.length > 1
+ // The tiles have exactly one source — the server aggregate on All, the trend read
+ // otherwise — so only that read's failure can explain them. Blaming either read let a
+ // failed trend beside a healthy stats call render 0 lb and claim it was stale data.
+ const tilesError = useServerAggregate ? statsError : chartError
+ const noValues = useServerAggregate ? stats!.total_entries === 0 : periodValues.length === 0
+ const figuresFailed = noValues && tilesError != null
+ const aggregatesUnknown = noValues && !figuresFailed
+ // We hold values, but the refresh that would have updated them failed. Keep them and
+ // say so — nothing else on screen tells the reader these numbers are out of date.
+ const figuresStale = !noValues && tilesError != null
+
const current = displayWeight(currentLbs, unit)
const change = displayWeight(changeLbs, unit)
const avg = displayWeight(avgLbs, unit)
@@ -190,6 +283,25 @@ export default function Weight() {
{ label: 'High', value: max, icon: ArrowUp, color: brand.errorSoft },
]
+ // Title and subtitle stay so the reader knows where they are; the unit chip does not,
+ // and neither does the log form — a save that cannot succeed would outrank the retry.
+ if (pageError != null) {
+ return (
+ <Screen>
+ <View className="flex-1 gap-5 py-4">
+ <PageHeader title="Weight" subtitle="Track your body weight over time" />
+ <ErrorState
+ size="page"
+ title="Couldn't load your weight"
+ message={pageError}
+ onRetry={retryAll}
+ retrying={retrying}
+ />
+ </View>
+ </Screen>
+ )
+ }
+
return (
<Screen>
<FlatList
@@ -314,7 +426,17 @@ export default function Weight() {
{/* Current-weight hero */}
<Card className="border-brand-500/20 bg-brand-500/5">
- {items.length === 0 ? (
+ {items.length === 0 && loadFailed ? (
+ // Empty and unreachable look identical from here, so the empty copy
+ // cannot be the default: it told someone with years of entries they had
+ // never weighed themselves.
+ <ErrorState
+ title="Couldn't load your weight"
+ message={listError ?? chartError ?? statsError ?? ''}
+ onRetry={retryAll}
+ retrying={retrying}
+ />
+ ) : items.length === 0 ? (
<View className="items-center py-2">
<Label className="mb-1">Current Weight</Label>
<AppText variant="body" color="muted">The scale doesn't know you exist yet. Fix that.</AppText>
@@ -325,20 +447,24 @@ export default function Weight() {
<View>
<Label className="mb-2">Current Weight</Label>
<View className="flex-row items-end gap-2">
- <AppText variant="display" style={{ fontSize: 40, lineHeight: 44, fontVariant: ['tabular-nums'] }}>{current}</AppText>
- <AppText variant="body" color="muted" className="mb-1.5">{wUnit}</AppText>
+ <AppText variant="display" style={{ fontSize: 40, lineHeight: 44, fontVariant: ['tabular-nums'] }}>{currentKnown ? current : '—'}</AppText>
+ {currentKnown ? <AppText variant="body" color="muted" className="mb-1.5">{wUnit}</AppText> : null}
</View>
</View>
- <View className={`flex-row items-center gap-1.5 rounded-lg border px-3 py-1.5 ${trendPill}`}>
- <TrendIcon size={16} color={trendText} />
- <Text className="font-sans-semibold text-sm" style={{ color: trendText, fontVariant: ['tabular-nums'] }}>
- {Math.abs(change)} {wUnit}
- </Text>
- </View>
+ {changeKnown ? (
+ <View className={`flex-row items-center gap-1.5 rounded-lg border px-3 py-1.5 ${trendPill}`}>
+ <TrendIcon size={16} color={trendText} />
+ <Text className="font-sans-semibold text-sm" style={{ color: trendText, fontVariant: ['tabular-nums'] }}>
+ {Math.abs(change)} {wUnit}
+ </Text>
+ </View>
+ ) : null}
</View>
- <AppText variant="caption" color="muted" className="mt-3">
- {Math.abs(change)} {wUnit} {changeWord} over {period}
- </AppText>
+ {changeKnown ? (
+ <AppText variant="caption" color="muted" className="mt-3">
+ {Math.abs(change)} {wUnit} {changeWord} over {period}
+ </AppText>
+ ) : null}
</>
)}
</Card>
@@ -351,14 +477,32 @@ export default function Weight() {
<s.icon size={14} color={s.color} />
<Label numberOfLines={1}>{s.label}</Label>
</View>
- <View className="flex-row items-end gap-1">
- <AppText variant="heading" style={{ fontVariant: ['tabular-nums'] }}>{Math.round(s.value)}</AppText>
- <AppText variant="caption" color="muted" className="mb-0.5">{wUnit}</AppText>
- </View>
+ {chartPending ? (
+ <Skeleton width={56} height={22} />
+ ) : figuresFailed ? (
+ <StatFailure label={`Couldn't load ${s.label.toLowerCase()} weight`} />
+ ) : (
+ <View className="flex-row items-end gap-1">
+ <AppText variant="heading" style={{ fontVariant: ['tabular-nums'] }}>{aggregatesUnknown ? '—' : Math.round(s.value)}</AppText>
+ {aggregatesUnknown ? null : <AppText variant="caption" color="muted" className="mb-0.5">{wUnit}</AppText>}
+ </View>
+ )}
</Card>
))}
</View>
+ {figuresStale ? (
+ <View className="flex-row flex-wrap items-center gap-2 px-1" accessibilityLiveRegion="polite">
+ {/* The same mark every other failure on this screen uses, in warning ink
+ rather than error: these numbers are real, just not fresh. */}
+ <BarbellBroken size={20} color={semanticInk[isDark ? 'dark' : 'light'].warning} />
+ <AppText variant="caption" color="muted">Couldn't refresh these — showing the last we loaded.</AppText>
+ <Pressable onPress={retryAll} hitSlop={8} accessibilityRole="button" className="active:opacity-60">
+ <AppText variant="caption" color="secondary" className="underline">Try again</AppText>
+ </Pressable>
+ </View>
+ ) : null}
+
{/* Chart + period selector */}
<Card>
<View className="mb-3 flex-row items-center justify-between gap-2">
@@ -368,7 +512,13 @@ export default function Weight() {
</View>
</View>
<View onLayout={(e) => setChartWidth(e.nativeEvent.layout.width)}>
- {chartData.length < 2 ? (
+ {chartPending ? (
+ <View className="h-44 justify-center gap-2 px-2">
+ <Skeleton width="100%" height={120} radius={12} />
+ </View>
+ ) : chartData.length === 0 && chartError ? (
+ <ErrorState title="Couldn't load your trend" message={chartError} onRetry={retryAll} retrying={retrying} />
+ ) : chartData.length < 2 ? (
<View className="h-44 items-center justify-center">
<AppText variant="body" color="muted">
{chartData.length === 0 ? 'No data for this period' : 'Log another entry to see the trend'}
@@ -392,7 +542,11 @@ export default function Weight() {
/>
)}
ListFooterComponent={
- hasMore && loading && items.length > 0 ? (
+ // Only under rows that arrived: with none, the hero above already carries the
+ // failure, and saying it twice is two retries for one problem.
+ listError && items.length > 0 ? (
+ <ErrorState title="Couldn't load more entries" message={listError} onRetry={retryList} />
+ ) : hasMore && loading && items.length > 0 ? (
<View className="items-center py-3">
<ActivityIndicator size="small" color={accent} />
</View>
diff --git a/mobile/app/(tabs)/workouts/[id].tsx b/mobile/app/(tabs)/workouts/[id].tsx
index a820e92..5d8527a 100644
--- a/mobile/app/(tabs)/workouts/[id].tsx
+++ b/mobile/app/(tabs)/workouts/[id].tsx
@@ -2,10 +2,10 @@ import { useEffect, useState } from 'react'
import { Pressable, ScrollView, View } from 'react-native'
import { router, useLocalSearchParams, type Href } from 'expo-router'
import {
- AlertCircle, ArrowLeft, ChevronRight, Clock, Edit2, Layers, Pause, TimerOff, Trash2, TrendingUp,
+ ArrowLeft, ChevronRight, Clock, Edit2, Layers, Pause, TimerOff, Trash2, TrendingUp,
} from 'lucide-react-native'
import { useAsyncAction, apiErrorMessage, displayVolume, displayWeight, weightShort, type Workout, type Set as WorkoutSet, workoutDay, restLabel, calcVolume, countWorkingSets, exerciseVolume, formatDay } from '@lyftr/shared'
-import { AppText, ConfirmSheet, Loading, Screen, deleteConfirmProps } from '../../../src/components/ui'
+import { AppText, Button, ConfirmSheet, ErrorState, Loading, Screen, deleteConfirmProps } from '../../../src/components/ui'
import { ExerciseImage } from '../../../src/components/workouts/ExerciseImage'
import { client, useSettingsStore } from '../../../src/lib/lyftr'
import { useTheme } from '../../../src/theme/useTheme'
@@ -54,11 +54,14 @@ export default function WorkoutDetail() {
const fetchSettings = useSettingsStore((s) => s.fetch)
const wUnit = weightShort(settings.weight_unit)
const restOn = settings.rest_enabled ?? true
- const { colors, brand, accent, isDark } = useTheme()
+ const { colors, accent } = useTheme()
const [workout, setWorkout] = useState<Workout | null>(null)
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
+ // Bumping this re-runs the load effect — three lines, rather than restructuring a
+ // working effect to gain a retry button.
+ const [retryKey, setRetryKey] = useState(0)
const [confirming, setConfirming] = useState(false)
useEffect(() => {
@@ -72,14 +75,14 @@ export default function WorkoutDetail() {
const data = await client.workoutAPI.get(Number(id))
if (!cancelled) setWorkout(data)
} catch (err) {
- if (!cancelled) setError(apiErrorMessage(err, 'Failed to load workout'))
+ if (!cancelled) setError(apiErrorMessage(err, "The server didn't say what went wrong."))
} finally {
if (!cancelled) setLoading(false)
}
}
load()
return () => { cancelled = true }
- }, [id])
+ }, [id, retryKey])
// Deep links can land here with no history — fall back to the list route.
const goBack = () => (router.canGoBack() ? router.back() : router.replace('/workouts'))
@@ -100,18 +103,14 @@ export default function WorkoutDetail() {
if (error || !workout) {
return (
<Screen>
- <View className="gap-4 py-4">
- <Pressable onPress={goBack} hitSlop={8} className="flex-row items-center gap-2 self-start active:opacity-60">
- <ArrowLeft size={16} color={colors.txMuted} />
- <AppText variant="body" color="muted">Back</AppText>
- </Pressable>
- {/* Boxed request-error alert (authui AuthError pattern) */}
- <View className="flex-row items-center gap-2 rounded-xl border border-error-500/20 bg-error-500/10 p-4">
- <AlertCircle size={20} color={isDark ? brand.errorSoft : brand.error} />
- <AppText variant="body" color="error" className="flex-1">
- {error || 'Workout not found'}
- </AppText>
- </View>
+ <View className="flex-1 py-4">
+ <ErrorState
+ size="page"
+ title="Couldn't load this workout"
+ message={error ?? 'That workout no longer exists.'}
+ onRetry={error ? () => { setError(null); setRetryKey((k) => k + 1) } : undefined}
+ secondary={<Button title="Back to workouts" variant="secondary" onPress={goBack} />}
+ />
</View>
</Screen>
)
diff --git a/mobile/app/(tabs)/workouts/[id]/edit.tsx b/mobile/app/(tabs)/workouts/[id]/edit.tsx
index 802bf06..016de9a 100644
--- a/mobile/app/(tabs)/workouts/[id]/edit.tsx
+++ b/mobile/app/(tabs)/workouts/[id]/edit.tsx
@@ -5,8 +5,8 @@ import {
AlertCircle, ArrowLeft, CalendarDays, Clock, Dumbbell, FileText, Plus, Zap,
} from 'lucide-react-native'
import type { LucideIcon } from 'lucide-react-native'
-import { useAsyncAction, dayToInstant, displayToLbs, lbsToDisplay, weightShort, type Exercise, workoutDay } from '@lyftr/shared'
-import { AppText, Button, DateInput, EmptyState, Field, IconButton, Label, Loading, Screen } from '../../../../src/components/ui'
+import { apiErrorMessage, useAsyncAction, dayToInstant, displayToLbs, lbsToDisplay, weightShort, type Exercise, workoutDay } from '@lyftr/shared'
+import { AppText, Button, DateInput, EmptyState, ErrorState, Field, IconButton, Label, Loading, Screen } from '../../../../src/components/ui'
import { ExerciseFormCard } from '../../../../src/components/workouts/ExerciseFormCard'
import { DurationField } from '../../../../src/components/workouts/DurationField'
import { ExercisePicker } from '../../../../src/components/workouts/ExercisePicker'
@@ -62,6 +62,10 @@ export default function EditWorkout() {
// Only what the FORM can say before anything is sent. What the SERVER says lives
// on `save` below; both render in the same alert.
const [error, setError] = useState('')
+ // Separate from `error`, which is this form's own validation. A load that never
+ // arrived is not a missing field — there is nothing to edit.
+ const [loadError, setLoadError] = useState<string | null>(null)
+ const [retryKey, setRetryKey] = useState(0)
const [pickerExercises, setPickerExercises] = useState<Record<number, Exercise>>({})
const [formData, setFormData] = useState<WorkoutFormData>({ name: '', notes: '', date: '', duration: 0, exercises: [] })
const [originalStartedAt, setOriginalStartedAt] = useState('')
@@ -108,11 +112,11 @@ export default function EditWorkout() {
})),
})
})
- .catch(() => setError('Failed to load workout'))
+ .catch((err) => setLoadError(apiErrorMessage(err, "The server didn't say what went wrong.")))
.finally(() => setInitialLoading(false))
// Web effect deps: [id] only — settings are fetched before a user can navigate here.
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [id])
+ }, [id, retryKey])
const goBack = () => (router.canGoBack() ? router.back() : router.replace('/workouts'))
@@ -210,6 +214,20 @@ export default function EditWorkout() {
void save.run()
}
+ if (loadError) {
+ return (
+ <Screen>
+ <ErrorState
+ size="page"
+ title="Couldn't load this workout"
+ message={loadError}
+ onRetry={() => { setLoadError(null); setRetryKey((k) => k + 1) }}
+ secondary={<Button title="Back to workouts" variant="secondary" onPress={goBack} />}
+ />
+ </Screen>
+ )
+ }
+
if (initialLoading) return <Loading />
diff --git a/mobile/app/(tabs)/workouts/index.tsx b/mobile/app/(tabs)/workouts/index.tsx
index 4f5278c..0e416e2 100644
--- a/mobile/app/(tabs)/workouts/index.tsx
+++ b/mobile/app/(tabs)/workouts/index.tsx
@@ -4,7 +4,7 @@ import { router, useFocusEffect, type Href } from 'expo-router'
import { Award, CheckCircle2, Dumbbell, Plus, RotateCcw, TrendingUp } from 'lucide-react-native'
import { format } from 'date-fns'
import { weightShort, workoutDay, type Workout } from '@lyftr/shared'
-import { AppText, Card, EmptyState, IconButton, Label, PageHeader, Screen, SearchField, Toast } from '../../../src/components/ui'
+import { AppText, Card, EmptyState, ErrorState, IconButton, StatFailure, Label, PageHeader, Screen, SearchField, Toast } from '../../../src/components/ui'
import { WorkoutCard } from '../../../src/components/workouts/WorkoutCard'
import { WorkoutsSkeleton } from '../../../src/components/workouts/WorkoutsSkeleton'
import { useServerInfiniteList } from '../../../src/hooks/useServerInfiniteList'
@@ -47,8 +47,10 @@ export default function Workouts() {
client.workoutAPI.list({ offset, limit, q: debouncedSearch || undefined }),
[debouncedSearch]
)
- const { items: workouts, loadMore, hasMore, loading, initialLoading, refreshing, reload } =
- useServerInfiniteList<Workout>({ fetcher, deps: [debouncedSearch] })
+ const {
+ items: workouts, loadMore, hasMore, loading, initialLoading, refreshing, reload,
+ error: listError, retry: retryList,
+ } = useServerInfiniteList<Workout>({ fetcher, deps: [debouncedSearch] })
// The stack keeps this screen mounted under the detail screen, so a delete made
// there doesn't remount us the way the web SPA's re-navigation does — refetch on
@@ -65,6 +67,19 @@ export default function Workouts() {
)
// Pull-to-refresh: drive the native RefreshControl spinner off the reload promise.
+ // Which query the rows on screen answer. Keeping the previous results while a new
+ // search runs is right — until that search fails, at which point the field says one
+ // thing and the rows below it another. Then they are not stale, they are a different
+ // query's answer, and the error takes their place.
+ const [answeredQuery, setAnsweredQuery] = useState('')
+ // Keyed on the hook's own loading flag, which is already true by the time this runs
+ // for a new query — `refreshing` is not, so this marked a query answered before its
+ // request had left, and a failure then kept the previous query's rows on screen.
+ useEffect(() => {
+ if (!loading && listError == null) setAnsweredQuery(debouncedSearch)
+ }, [loading, listError, debouncedSearch])
+ const queryAnswered = listError == null || answeredQuery === debouncedSearch
+
const [pulling, setPulling] = useState(false)
const onPullRefresh = useCallback(async () => {
setPulling(true)
@@ -76,16 +91,93 @@ export default function Workouts() {
// placeholders read as faster and match where the real cards will land.
if (initialLoading) return <WorkoutsSkeleton />
+ // Post-session confirmation. Saved = quiet success; discarded = tap-to-undo
+ // (restores the exact session snapshot and drops you back into it). Built before the
+ // early return so a list that fails to load does not swallow the outcome of a session.
+ const outcomeToast = outcome ? (
+ outcome.kind === 'saved' ? (
+ outcome.progression ? (
+ <Toast
+ variant={outcome.progression.is_pr ? 'warning' : 'success'}
+ icon={outcome.progression.is_pr ? Award : TrendingUp}
+ title={outcome.progression.is_pr ? `New PR in ${outcome.progression.program_name}` : `New targets in ${outcome.progression.program_name}`}
+ description={`Tap to review ${outcome.progression.count} ${outcome.progression.count === 1 ? 'update' : 'updates'}`}
+ onPress={() => {
+ const programId = outcome.progression!.program_id
+ clearOutcome()
+ router.navigate(programHref(programId))
+ }}
+ onDismiss={clearOutcome}
+ />
+ ) : (
+ <Toast
+ variant="success"
+ icon={CheckCircle2}
+ title="Workout saved"
+ description="Tap to view"
+ onPress={() => {
+ clearOutcome()
+ router.push(`/workouts/${outcome.workoutId}`)
+ }}
+ onDismiss={clearOutcome}
+ />
+ )
+ ) : (
+ <Toast
+ variant="default"
+ icon={RotateCcw}
+ title="Workout discarded"
+ description="Tap to undo"
+ onPress={() => {
+ restoreSession(outcome.session)
+ clearOutcome()
+ router.push('/workouts/active')
+ }}
+ onDismiss={clearOutcome}
+ />
+ )
+ ) : null
+
+ // Nothing arrived, so there is no screen to draw around the failure. One error for the
+ // page, under the same title; a later page failing under loaded rows is the footer's.
+ //
+ // Not while a search is running, though: taking the whole screen takes the field the
+ // query was typed into, so the query cannot be cleared or changed and retry can only
+ // re-run the request that just failed. A search that fails keeps its search bar.
+ if (listError && workouts.length === 0 && !debouncedSearch) {
+ return (
+ <Screen>
+ <View className="flex-1 gap-5 py-4">
+ <PageHeader title="Workouts" subtitle="Track and review your training sessions" />
+ <ErrorState size="page" title="Couldn't load your workouts" message={listError} onRetry={retryList} retrying={loading} />
+ </View>
+ {outcomeToast}
+ </Screen>
+ )
+ }
const now = new Date()
+ const mayHaveMore = hasMore || listError != null
+ // Nothing loaded and the read failed: these tiles have no figure to round down to.
+ // "0+ logged" is true of every account that ever existed, which is another way of
+ // saying nothing. Reached with a search on screen; otherwise the page error owns this.
+ const countsUnknown = listError != null && (workouts.length === 0 || !queryAnswered)
+ const month = format(now, 'yyyy-MM')
+ const thisMonth = workouts.filter((w) => workoutDay(w).startsWith(month)).length
+ const oldestLoadedDay = workouts.length > 0 ? workoutDay(workouts[workouts.length - 1]) : null
+ const monthCountKnown = !mayHaveMore || (oldestLoadedDay != null && oldestLoadedDay < `${month}-01`)
const stats = [
- // 1:1 with web: these summarize the *loaded* items, not a server-side stat.
- { label: 'Total', value: String(workouts.length), unit: 'logged' },
+ // These summarize the *loaded* items; while pages remain, the total is a lower bound.
+ // A failed page counts as "pages remain": the hook drops hasMore on error, and
+ // without listError here a dropped connection made the count look more certain.
+ { label: 'Total', value: mayHaveMore ? `${workouts.length}+` : String(workouts.length), unit: 'logged' },
{
label: 'This Month',
// The month the workout was logged in, not the month its UTC instant lands in —
// a session near a month boundary belongs to the month the lifter trained in.
- value: String(workouts.filter((w) => workoutDay(w).startsWith(format(now, 'yyyy-MM'))).length),
+ // Newest-first paging means we have seen the whole month only once a loaded row
+ // predates it; until then the count is a lower bound and says so, like Total.
+ value: monthCountKnown ? String(thisMonth) : `${thisMonth}+`,
unit: 'sessions',
},
{
@@ -93,7 +185,7 @@ export default function Workouts() {
value:
workouts.length > 0
? String(Math.round(workouts.reduce((sum, w) => sum + w.duration, 0) / workouts.length / 60))
- : '0',
+ : '—',
unit: 'min',
},
]
@@ -101,7 +193,7 @@ export default function Workouts() {
return (
<Screen>
<FlatList
- data={workouts}
+ data={queryAnswered ? workouts : []}
keyExtractor={(w) => String(w.id)}
showsVerticalScrollIndicator={false}
contentContainerStyle={{ paddingBottom: 32 }}
@@ -140,6 +232,9 @@ export default function Workouts() {
{stats.map((s) => (
<Card key={s.label} className="flex-1 rounded-2xl" style={{ paddingHorizontal: 12 }}>
<Label className="mb-2" numberOfLines={1}>{s.label}</Label>
+ {countsUnknown ? (
+ <StatFailure label={`Couldn't load ${s.label.toLowerCase()}`} />
+ ) : (
<View className="flex-row items-end gap-1">
<AppText variant="heading" style={{ fontVariant: ['tabular-nums'] }}>
{s.value}
@@ -148,6 +243,7 @@ export default function Workouts() {
{s.unit}
</AppText>
</View>
+ )}
</Card>
))}
</View>
@@ -176,7 +272,11 @@ export default function Workouts() {
</View>
)}
ListEmptyComponent={
- loading ? null : (
+ loading ? null : listError ? (
+ // Reached only with a search on screen (the early return covers the rest):
+ // "No workouts found" would blame the query for a request that never landed.
+ <ErrorState title="Couldn't load your workouts" message={listError} onRetry={retryList} retrying={loading} />
+ ) : (
<EmptyState
icon={Dumbbell}
title="No workouts found"
@@ -185,7 +285,9 @@ export default function Workouts() {
)
}
ListFooterComponent={
- hasMore && loading && workouts.length > 0 ? (
+ listError && workouts.length > 0 ? (
+ <ErrorState title="Couldn't load your workouts" message={listError} onRetry={retryList} retrying={loading} />
+ ) : hasMore && loading && workouts.length > 0 ? (
<View className="items-center py-3">
<ActivityIndicator size="small" color={accent} />
</View>
@@ -193,51 +295,7 @@ export default function Workouts() {
}
/>
- {/* Post-session confirmation. Saved = quiet success; discarded = tap-to-undo
- (restores the exact session snapshot and drops you back into it). */}
- {outcome ? (
- outcome.kind === 'saved' ? (
- outcome.progression ? (
- <Toast
- variant={outcome.progression.is_pr ? 'warning' : 'success'}
- icon={outcome.progression.is_pr ? Award : TrendingUp}
- title={outcome.progression.is_pr ? `New PR in ${outcome.progression.program_name}` : `New targets in ${outcome.progression.program_name}`}
- description={`Tap to review ${outcome.progression.count} ${outcome.progression.count === 1 ? 'update' : 'updates'}`}
- onPress={() => {
- const programId = outcome.progression!.program_id
- clearOutcome()
- router.navigate(programHref(programId))
- }}
- onDismiss={clearOutcome}
- />
- ) : (
- <Toast
- variant="success"
- icon={CheckCircle2}
- title="Workout saved"
- description="Tap to view"
- onPress={() => {
- clearOutcome()
- router.push(`/workouts/${outcome.workoutId}`)
- }}
- onDismiss={clearOutcome}
- />
- )
- ) : (
- <Toast
- variant="default"
- icon={RotateCcw}
- title="Workout discarded"
- description="Tap to undo"
- onPress={() => {
- restoreSession(outcome.session)
- clearOutcome()
- router.push('/workouts/active')
- }}
- onDismiss={clearOutcome}
- />
- )
- ) : null}
+ {outcomeToast}
</Screen>
)
}
diff --git a/mobile/app/(tabs)/workouts/start.tsx b/mobile/app/(tabs)/workouts/start.tsx
index 004cbf7..35829c7 100644
--- a/mobile/app/(tabs)/workouts/start.tsx
+++ b/mobile/app/(tabs)/workouts/start.tsx
@@ -3,8 +3,8 @@ import { ActivityIndicator, Pressable, ScrollView, View } from 'react-native'
import { router } from 'expo-router'
import { ArrowLeft, BookOpen, ChevronRight, Play, Timer, Trash2, Zap } from 'lucide-react-native'
import type { Program, ProgramDay } from '@lyftr/shared'
-import { activeSessionExercisesForDay, sessionNameForDay } from '@lyftr/shared'
-import { AppText, IconButton, Screen } from '../../../src/components/ui'
+import { apiErrorMessage, activeSessionExercisesForDay, sessionNameForDay } from '@lyftr/shared'
+import { AppText, ErrorState, IconButton, Screen } from '../../../src/components/ui'
import { DayPickerSheet, pickProgramDay } from '../../../src/components/programs/DayPickerSheet'
import { client, useWorkoutSession } from '../../../src/lib/lyftr'
import { useTheme } from '../../../src/theme/useTheme'
@@ -21,6 +21,7 @@ export default function StartWorkout() {
const [programs, setPrograms] = useState<Program[]>([])
const [loading, setLoading] = useState(false)
const [error, setError] = useState('')
+ const [retryKey, setRetryKey] = useState(0)
const [dayPickFor, setDayPickFor] = useState<Program | null>(null)
useEffect(() => {
@@ -28,9 +29,9 @@ export default function StartWorkout() {
client.programAPI
.list()
.then((data) => setPrograms(data || []))
- .catch(() => setError('Failed to load programs'))
+ .catch((err) => setError(apiErrorMessage(err, "The server didn't say what went wrong.")))
.finally(() => setLoading(false))
- }, [])
+ }, [retryKey])
const goBack = () => (router.canGoBack() ? router.back() : router.replace('/workouts'))
@@ -108,10 +109,15 @@ export default function StartWorkout() {
<AppText variant="subheading">Start from Program</AppText>
</View>
+ {/* Section-scoped: starting an empty workout does not need this list, so
+ only the program picker area is replaced. */}
{error ? (
- <View className="mb-3 rounded-xl border border-error-500/20 bg-error-500/10 p-4">
- <AppText variant="body" color="error">{error}</AppText>
- </View>
+ <ErrorState
+ size="section"
+ title="Couldn't load your programs"
+ message={error}
+ onRetry={() => { setError(''); setRetryKey((k) => k + 1) }}
+ />
) : null}
{loading ? (
@@ -119,6 +125,11 @@ export default function StartWorkout() {
<ActivityIndicator color={accent} />
<AppText variant="body" color="muted">Loading programs…</AppText>
</View>
+ ) : error ? (
+ // The error above already owns this space. Stacking "No programs yet"
+ // under it tells a reader with ten programs both that the load failed and
+ // that they have none.
+ null
) : programs.length === 0 ? (
<View className="items-center rounded-2xl border border-surface-border bg-surface-raised py-10">
<BookOpen size={32} color={colors.txMuted} />
diff --git a/mobile/src/components/dashboard/QuickWeighInSheet.tsx b/mobile/src/components/dashboard/QuickWeighInSheet.tsx
index 5422911..84ff243 100644
--- a/mobile/src/components/dashboard/QuickWeighInSheet.tsx
+++ b/mobile/src/components/dashboard/QuickWeighInSheet.tsx
@@ -110,7 +110,7 @@ export function QuickWeighInSheet({ open, lastValue, lastLog, onClose, onSuccess
},
]}
>
- Already logged today ({Math.round(lastValue ?? 0)} {wUnit}). Log again anyway?
+ Already logged today ({lastValue} {wUnit}). Log again anyway?
</Alert>
) : null}
diff --git a/mobile/src/components/ui/ErrorState.tsx b/mobile/src/components/ui/ErrorState.tsx
index 8ea3799..06fd8f5 100644
--- a/mobile/src/components/ui/ErrorState.tsx
+++ b/mobile/src/components/ui/ErrorState.tsx
@@ -25,6 +25,9 @@ interface Props {
size?: 'page' | 'section'
onRetry?: () => void
retryLabel?: string
+ /** The retry is in flight. Without it the button looks untouched on a slow server,
+ and the only feedback is the screen rearranging around a request nobody can see. */
+ retrying?: boolean
/** One escape hatch at most, for when retrying is not the answer. */
secondary?: ReactNode
}
@@ -35,6 +38,7 @@ export function ErrorState({
size = 'section',
onRetry,
retryLabel = 'Try again',
+ retrying = false,
secondary,
}: Props) {
const { isDark } = useTheme()
@@ -65,7 +69,9 @@ export function ErrorState({
</View>
{onRetry || secondary ? (
<View className="mt-1 flex-row flex-wrap items-center justify-center gap-2">
- {onRetry ? <Button title={retryLabel} onPress={onRetry} /> : null}
+ {onRetry ? (
+ <Button title={retrying ? 'Retrying…' : retryLabel} onPress={onRetry} loading={retrying} disabled={retrying} />
+ ) : null}
{secondary}
</View>
) : null}
diff --git a/mobile/src/components/ui/StatFailure.tsx b/mobile/src/components/ui/StatFailure.tsx
new file mode 100644
index 0000000..da31f01
--- /dev/null
+++ b/mobile/src/components/ui/StatFailure.tsx
@@ -0,0 +1,16 @@
+import { View } from 'react-native'
+import { semanticInk } from '../../theme/theme'
+import { useTheme } from '../../theme/useTheme'
+import { BarbellBroken } from './BarbellBroken'
+
+// A stat tile whose figure could not be loaded. Mirrors web ui/StatFailure: the dropped
+// barbell at tile-figure size, no words — the tile's own label already says what is
+// missing, and a 0 in its place would claim a figure we never got.
+export function StatFailure({ label = "Couldn't load this figure" }: { label?: string }) {
+ const { isDark } = useTheme()
+ return (
+ <View accessible accessibilityRole="image" accessibilityLabel={label}>
+ <BarbellBroken size={26} color={semanticInk[isDark ? 'dark' : 'light'].error} />
+ </View>
+ )
+}
diff --git a/mobile/src/components/ui/index.ts b/mobile/src/components/ui/index.ts
index 8e5d9fc..c2fa8a7 100644
--- a/mobile/src/components/ui/index.ts
+++ b/mobile/src/components/ui/index.ts
@@ -10,6 +10,9 @@ export type { AppTextProps, TextVariant, TextColor } from './Typography'
export { Screen } from './Screen'
export { Card } from './Card'
export { Alert } from './Alert'
+export { ErrorState } from './ErrorState'
+export { BarbellBroken } from './BarbellBroken'
+export { StatFailure } from './StatFailure'
// Headers (web-parity)
export { PageHeader } from './PageHeader'
diff --git a/mobile/src/components/workouts/ExerciseDetailScreen.tsx b/mobile/src/components/workouts/ExerciseDetailScreen.tsx
index 648cd74..70246f8 100644
--- a/mobile/src/components/workouts/ExerciseDetailScreen.tsx
+++ b/mobile/src/components/workouts/ExerciseDetailScreen.tsx
@@ -14,13 +14,14 @@ import Animated, {
withTiming,
} from 'react-native-reanimated'
import {
+ apiErrorMessage,
displayWeight,
weightShort,
type Exercise,
type ExerciseHistoryPoint,
type PersonalRecord,
} from '@lyftr/shared'
-import { AppText, Screen, SegmentedControl } from '../ui'
+import { AppText, Button, ErrorState, Screen, SegmentedControl } from '../ui'
import { MuscleDiagram } from './MuscleDiagram'
import { ExerciseHistoryChart, type ChartPoint } from './ExerciseHistoryChart'
import { client, useSettingsStore, useWorkoutSession } from '../../lib/lyftr'
@@ -100,6 +101,10 @@ export function ExerciseDetailScreen({ backFallback }: { backFallback: Href }) {
const [historyPeriod, setHistoryPeriod] = useState<HistoryPeriod>('3m')
const [imgFailed, setImgFailed] = useState(false)
const [loading, setLoading] = useState(true)
+ const [error, setError] = useState<string | null>(null)
+ // Bumping this re-runs the load effect — three lines, rather than restructuring a
+ // working effect to gain a retry button.
+ const [retryKey, setRetryKey] = useState(0)
const [chartWidth, setChartWidth] = useState(0)
useEffect(() => {
@@ -121,11 +126,11 @@ export function ExerciseDetailScreen({ backFallback }: { backFallback: Href }) {
setPR(prData)
setHistory(histData || [])
})
- .catch(() => { if (!cancelled) goBack() })
+ .catch((err) => { if (!cancelled) setError(apiErrorMessage(err, "The server didn't say what went wrong.")) })
.finally(() => { if (!cancelled) setLoading(false) })
return () => { cancelled = true }
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [exerciseId])
+ }, [exerciseId, retryKey])
const filteredHistory = useMemo(() => {
const days = HISTORY_DAYS[historyPeriod]
@@ -134,6 +139,22 @@ export function ExerciseDetailScreen({ backFallback }: { backFallback: Href }) {
return history.filter((h) => new Date(h.date).getTime() >= cutoff)
}, [history, historyPeriod])
+ // A dropped connection used to goBack() — off the screen, no explanation, nothing to
+ // retry. Say what happened and leave them where they tapped.
+ if (error) {
+ return (
+ <Screen>
+ <ErrorState
+ size="page"
+ title="Couldn't load this exercise"
+ message={error}
+ onRetry={() => { setError(null); setRetryKey((k) => k + 1) }}
+ secondary={<Button title="Go back" variant="secondary" onPress={goBack} />}
+ />
+ </Screen>
+ )
+ }
+
if (loading || !exercise) return <LoadingPulse />
const equipLabel = EQUIPMENT_LABEL[exercise.equipment?.toLowerCase()] || exercise.equipment
diff --git a/mobile/src/components/workouts/ExercisePicker.tsx b/mobile/src/components/workouts/ExercisePicker.tsx
index db1ca49..fee062d 100644
--- a/mobile/src/components/workouts/ExercisePicker.tsx
+++ b/mobile/src/components/workouts/ExercisePicker.tsx
@@ -3,7 +3,7 @@ import { ActivityIndicator, FlatList, Modal, Pressable, TextInput, View } from '
import { SafeAreaProvider, SafeAreaView } from 'react-native-safe-area-context'
import { ArrowLeft, Search } from 'lucide-react-native'
import type { Exercise } from '@lyftr/shared'
-import { AppText, IconButton } from '../ui'
+import { AppText, ErrorState, IconButton } from '../ui'
import { client } from '../../lib/lyftr'
import { useServerInfiniteList } from '../../hooks/useServerInfiniteList'
import { useTheme } from '../../theme/useTheme'
@@ -78,7 +78,9 @@ export function ExercisePicker({ selectedIds, onSelect, onClose }: Props) {
[debouncedQuery]
)
- const { items: exercises, loadMore, hasMore, initialLoading } = useServerInfiniteList<Exercise>({
+ const {
+ items: exercises, loadMore, hasMore, initialLoading, error: listError, retry: retryList,
+ } = useServerInfiniteList<Exercise>({
fetcher,
pageSize: PAGE_SIZE,
deps: [debouncedQuery],
@@ -101,9 +103,13 @@ export function ExercisePicker({ selectedIds, onSelect, onClose }: Props) {
{/* Large title (matches the sibling "Log Workout" screen title) — the
18px heading read undersized for a full-screen surface. */}
<AppText variant="title">Add Exercise</AppText>
- <AppText variant="caption" color="muted">
- {available.length} loaded{hasMore ? '…' : ''}
- </AppText>
+ {/* Only true if the fetch landed — on a failure this read "0 loaded"
+ above a message saying we could not load anything. */}
+ {listError ? null : (
+ <AppText variant="caption" color="muted">
+ {available.length} loaded{hasMore ? '…' : ''}
+ </AppText>
+ )}
</View>
</View>
@@ -149,12 +155,25 @@ export function ExercisePicker({ selectedIds, onSelect, onClose }: Props) {
onEndReached={loadMore}
onEndReachedThreshold={0.5}
ListEmptyComponent={
- <View className="items-center py-16">
- <AppText variant="body" color="muted">No exercises found</AppText>
- </View>
+ // "No exercises found" is only true if we heard back. On a failed fetch
+ // it reads as an empty catalogue rather than a connection that dropped.
+ listError ? (
+ <ErrorState title="Couldn't load exercises" message={listError} onRetry={retryList} />
+ ) : (
+ <View className="items-center py-16">
+ <AppText variant="body" color="muted">No exercises found</AppText>
+ </View>
+ )
}
ListFooterComponent={
- hasMore && exercises.length > 0 ? (
+ // A later page failing under rows that did arrive: without this the list
+ // just stops, which reads as the end of the catalogue.
+ // Keyed on the rows actually listed, not on what loaded: with every loaded
+ // exercise already selected the list is empty, and the slot above would
+ // render the same failure a second time.
+ listError && available.length > 0 ? (
+ <ErrorState title="Couldn't load more exercises" message={listError} onRetry={retryList} />
+ ) : hasMore && available.length > 0 ? (
<View className="flex-row items-center justify-center gap-2 py-4">
<ActivityIndicator color={accent} />
<AppText variant="caption" color="muted">Loading more…</AppText>
diff --git a/mobile/src/components/workouts/ProgramPicker.tsx b/mobile/src/components/workouts/ProgramPicker.tsx
index bfc627b..6b18cd6 100644
--- a/mobile/src/components/workouts/ProgramPicker.tsx
+++ b/mobile/src/components/workouts/ProgramPicker.tsx
@@ -1,9 +1,9 @@
import { useEffect, useMemo, useState } from 'react'
import { ActivityIndicator, FlatList, Modal, Pressable, View } from 'react-native'
-import { AlertCircle, BookOpen, ChevronRight, Dumbbell, Moon, X } from 'lucide-react-native'
+import { BookOpen, ChevronRight, Dumbbell, Moon, X } from 'lucide-react-native'
import type { Program, ProgramDay } from '@lyftr/shared'
-import { workoutDays, dayLabel, todaysDay } from '@lyftr/shared'
-import { AppText, EmptyState, Field, IconButton } from '../ui'
+import { apiErrorMessage, workoutDays, dayLabel, todaysDay } from '@lyftr/shared'
+import { AppText, EmptyState, ErrorState, Field, IconButton } from '../ui'
import { client } from '../../lib/lyftr'
import { useTheme } from '../../theme/useTheme'
import { pickProgramDay } from '../programs/DayPickerSheet'
@@ -18,19 +18,21 @@ interface Props {
// skips the day step, same as web). One directed addition over web: a search field —
// client-side name filter, since the program list is a single un-paginated fetch.
export function ProgramPicker({ onSelect, onClose }: Props) {
- const { colors, brand, accent, isDark } = useTheme()
+ const { colors, accent } = useTheme()
const [programs, setPrograms] = useState<Program[]>([])
const [query, setQuery] = useState('')
const [loading, setLoading] = useState(true)
const [error, setError] = useState('')
const [dayPickFor, setDayPickFor] = useState<Program | null>(null)
+ const [retryKey, setRetryKey] = useState(0)
useEffect(() => {
+ setLoading(true)
client.programAPI.list()
- .then((data) => setPrograms(data || []))
- .catch(() => setError('Failed to load programs'))
+ .then((data) => { setPrograms(data || []); setError('') })
+ .catch((err) => setError(apiErrorMessage(err, "Couldn't load your programs.")))
.finally(() => setLoading(false))
- }, [])
+ }, [retryKey])
const shown = useMemo(() => {
const q = query.trim().toLowerCase()
@@ -116,10 +118,11 @@ export function ProgramPicker({ onSelect, onClose }: Props) {
<AppText variant="body" color="muted">Loading programs…</AppText>
</View>
) : error ? (
- <View className="flex-row items-center gap-2 p-4">
- <AlertCircle size={16} color={isDark ? brand.errorSoft : brand.error} />
- <AppText variant="body" color="error">{error}</AppText>
- </View>
+ <ErrorState
+ title="Couldn't load your programs"
+ message={error}
+ onRetry={() => setRetryKey((k) => k + 1)}
+ />
) : shown.length === 0 ? (
<EmptyState
compact
diff --git a/mobile/src/lib/errorSurfacing.guard.test.ts b/mobile/src/lib/errorSurfacing.guard.test.ts
new file mode 100644
index 0000000..9bcb7d2
--- /dev/null
+++ b/mobile/src/lib/errorSurfacing.guard.test.ts
@@ -0,0 +1,31 @@
+import { offenders } from '../testing/sourceScan'
+
+// #145 was "the button is dead" — a request that never settled. The audit that followed found
+// the quieter half of the same class: fourteen handlers that DID settle but threw the error
+// away, so a timeout, a cleartext block or a bad certificate all read as "Failed to load".
+// apiErrorMessage exists precisely to name those, and it cannot name what it is not given.
+//
+// A handler that takes no argument has nothing to grep for — `err.message` was the search that
+// missed all fourteen. So the guard is on the shape instead: if a catch produces user-facing
+// feedback, it must bind the error.
+//
+// Swallowing is still fine where nothing is shown — `Haptics.selectionAsync().catch(() => {})`
+// is a genuine don't-care, and this deliberately does not flag it.
+
+const PATTERNS = [
+ // .catch(() => setError('…')) — a message with the reason discarded.
+ /\.catch\(\(\)\s*=>[^\n]*set\w*Error\(/,
+ // } catch {
+ // setError('…')
+ /\}\s*catch\s*\{\n\s*set\w*Error\(/,
+ // .catch(() => goBack()) — bounced off the screen, no explanation, nothing to retry.
+ // router.replace and .push count too: the first draft of this guard listed only
+ // goBack/back, and walked straight past nutrition/log.tsx, which answered a failed
+ // edit-load by replacing the route. Any navigation away from the failure is the
+ // same eviction — the user loses the screen and is told nothing.
+ /\.catch\(\(\)\s*=>[^\n]*(goBack\(\)|router\.(back|replace|push)\()/,
+]
+
+it('never surfaces a failure it threw the cause away for', () => {
+ expect(offenders(PATTERNS)).toEqual([])
+})
diff --git a/mobile/src/lib/useAsyncAction.test.ts b/mobile/src/lib/useAsyncAction.test.ts
new file mode 100644
index 0000000..ab496cb
--- /dev/null
+++ b/mobile/src/lib/useAsyncAction.test.ts
@@ -0,0 +1,144 @@
+import { renderHook, act, waitFor } from '@testing-library/react-native'
+import { useAsyncAction } from '@lyftr/shared'
+
+// The hook lives in @lyftr/shared, but its test lives here: `packages/shared` is plain
+// ts-jest with no renderer, and adding one for this would be a dependency the repo does
+// not need. Mobile already has @testing-library/react-native, and mobile is where the
+// forty call sites this replaces mostly are.
+
+const httpError = (status: number, body: any = {}) => {
+ const err: any = new Error(`Request failed with status code ${status}`)
+ err.response = { status, data: body, statusText: '', headers: {}, config: {} }
+ return err
+}
+
+// No `response` at all — the shape a timeout or a dropped connection arrives in, and the
+// one every hand-rolled `err.response.data.error` read fell through on.
+const silence = () => {
+ const err: any = new Error('timeout of 20000ms exceeded')
+ err.code = 'ECONNABORTED'
+ return err
+}
+
+describe('useAsyncAction', () => {
+ it('reports busy while in flight and clears it after', async () => {
+ let release: () => void = () => {}
+ const action = jest.fn(() => new Promise<void>((resolve) => { release = resolve }))
+ const { result } = renderHook(() => useAsyncAction(action, 'Failed'))
+
+ expect(result.current.busy).toBe(false)
+ act(() => { void result.current.run() })
+ await waitFor(() => expect(result.current.busy).toBe(true))
+
+ await act(async () => { release() })
+ expect(result.current.busy).toBe(false)
+ expect(result.current.error).toBe('')
+ })
+
+ // Clearing in `finally` rather than only on failure: a screen that stays put after
+ // succeeding would otherwise read "Saving…" for the rest of its life.
+ it('clears busy on success too, not just on failure', async () => {
+ const { result } = renderHook(() => useAsyncAction(async () => {}, 'Failed'))
+
+ await act(async () => { await result.current.run() })
+
+ expect(result.current.busy).toBe(false)
+ })
+
+ it('resolves true on success and false on failure', async () => {
+ const ok = renderHook(() => useAsyncAction(async () => {}, 'Failed'))
+ const bad = renderHook(() => useAsyncAction(async () => { throw silence() }, 'Failed'))
+
+ let okResult: boolean | undefined
+ let badResult: boolean | undefined
+ await act(async () => { okResult = await ok.result.current.run() })
+ await act(async () => { badResult = await bad.result.current.run() })
+
+ expect(okResult).toBe(true)
+ expect(badResult).toBe(false)
+ })
+
+ it('prefers the message the server sent', async () => {
+ const { result } = renderHook(() =>
+ useAsyncAction(async () => { throw httpError(400, { error: 'name is required' }) }, 'Failed to save'))
+
+ await act(async () => { await result.current.run() })
+
+ expect(result.current.error).toBe('name is required')
+ })
+
+ // The whole reason apiErrorMessage lives inside the hook. A raw
+ // `err.response.data.error || 'Failed to save'` renders "Failed to save" here, which
+ // tells a user on bad wifi nothing about why or whether to try again.
+ it('explains a failure that carries no response, instead of falling back', async () => {
+ const { result } = renderHook(() =>
+ useAsyncAction(async () => { throw silence() }, 'Failed to save'))
+
+ await act(async () => { await result.current.run() })
+
+ expect(result.current.error).not.toBe('Failed to save')
+ expect(result.current.error).toMatch(/server/i)
+ })
+
+ it('falls back only when the error says nothing useful', async () => {
+ const { result } = renderHook(() =>
+ useAsyncAction(async () => { throw httpError(400) }, 'Failed to save'))
+
+ await act(async () => { await result.current.run() })
+
+ expect(result.current.error).toBe('Failed to save')
+ })
+
+ it('drops a stale message when the next attempt starts', async () => {
+ let fail = true
+ const { result } = renderHook(() =>
+ useAsyncAction(async () => { if (fail) throw silence() }, 'Failed'))
+
+ await act(async () => { await result.current.run() })
+ expect(result.current.error).not.toBe('')
+
+ fail = false
+ await act(async () => { await result.current.run() })
+ expect(result.current.error).toBe('')
+ })
+
+ it('drops a stale message on reset, for a sheet being dismissed', async () => {
+ const { result } = renderHook(() =>
+ useAsyncAction(async () => { throw silence() }, 'Failed'))
+
+ await act(async () => { await result.current.run() })
+ expect(result.current.error).not.toBe('')
+
+ act(() => result.current.reset())
+ expect(result.current.error).toBe('')
+ })
+
+ // `run` is handed to memoized rows and cards, and the screens it lives on re-render
+ // every second (the workout timer). If its identity changed with the inline closure
+ // it is given, every one of those children would re-render on every tick.
+ it('keeps run stable across renders while still calling the newest closure', async () => {
+ let calls = 0
+ let token = 'first'
+ const { result, rerender } = renderHook(
+ ({ t }: { t: string }) => useAsyncAction(async () => { calls += 1; token = t }, 'Failed'),
+ { initialProps: { t: 'first' } },
+ )
+ const firstRun = result.current.run
+
+ rerender({ t: 'second' })
+ expect(result.current.run).toBe(firstRun)
+
+ await act(async () => { await result.current.run() })
+ expect(calls).toBe(1)
+ expect(token).toBe('second')
+ })
+
+ it('passes its arguments through to the action', async () => {
+ const action = jest.fn(async (_id: number, _name: string) => {})
+ const { result } = renderHook(() => useAsyncAction(action, 'Failed'))
+
+ await act(async () => { await result.current.run(7, 'squat') })
+
+ expect(action).toHaveBeenCalledWith(7, 'squat')
+ })
+})
diff --git a/mobile/src/lib/useServerList.test.ts b/mobile/src/lib/useServerList.test.ts
new file mode 100644
index 0000000..1585304
--- /dev/null
+++ b/mobile/src/lib/useServerList.test.ts
@@ -0,0 +1,96 @@
+import { renderHook, act, waitFor } from '@testing-library/react-native'
+import { useServerList } from '@lyftr/shared'
+
+// Lives here for the same reason useAsyncAction.test.ts does: packages/shared is plain
+// ts-jest with no renderer, and mobile already has @testing-library/react-native.
+//
+// What is pinned is the distinction the hook could not previously make. A failed page
+// used to set hasMore=false and nothing else, which renders *identically* to reaching
+// the end of the data — so a dropped connection read as "that's all there is", and an
+// empty first page read as "you have no workouts" to someone with months of them.
+
+const page = (n: number, size: number) => Array.from({ length: size }, (_, i) => n * size + i)
+
+const timeout = () => {
+ const err: any = new Error('timeout of 20000ms exceeded')
+ err.code = 'ECONNABORTED'
+ return err
+}
+
+describe('useServerList — a page that never arrived', () => {
+ it('reports why the first page failed instead of looking empty', async () => {
+ const fetcher = jest.fn().mockRejectedValue(timeout())
+
+ const { result } = renderHook(() => useServerList<number>({ fetcher, pageSize: 2 }))
+
+ await waitFor(() => expect(result.current.error).toBeTruthy())
+ expect(result.current.items).toEqual([])
+ // The fallback would be wrong here — a timeout has no response body, and the whole
+ // point is that the screen can tell this apart from a genuinely empty list.
+ expect(result.current.error).toBe("The server didn't respond in time. Try again in a moment.")
+ })
+
+ it('keeps the pages that did arrive when a later one fails', async () => {
+ const fetcher = jest.fn()
+ .mockResolvedValueOnce(page(0, 2))
+ .mockRejectedValueOnce(timeout())
+
+ const { result } = renderHook(() => useServerList<number>({ fetcher, pageSize: 2 }))
+
+ await waitFor(() => expect(result.current.items).toEqual([0, 1]))
+
+ act(() => { result.current.loadMore() })
+
+ await waitFor(() => expect(result.current.error).toBeTruthy())
+ expect(result.current.items).toEqual([0, 1])
+ expect(result.current.hasMore).toBe(false)
+ })
+
+ it('resumes from where it stopped, without discarding what loaded', async () => {
+ const fetcher = jest.fn()
+ .mockResolvedValueOnce(page(0, 2))
+ .mockRejectedValueOnce(timeout())
+ .mockResolvedValueOnce(page(1, 2))
+
+ const { result } = renderHook(() => useServerList<number>({ fetcher, pageSize: 2 }))
+ await waitFor(() => expect(result.current.items).toEqual([0, 1]))
+
+ act(() => { result.current.loadMore() })
+ await waitFor(() => expect(result.current.error).toBeTruthy())
+
+ act(() => { result.current.retry() })
+
+ // Appends rather than replaces: retry is a resume, so the two rows already on screen
+ // are not thrown away to recover the page that failed.
+ await waitFor(() => expect(result.current.items).toEqual([0, 1, 2, 3]))
+ expect(result.current.error).toBeNull()
+ expect(result.current.hasMore).toBe(true)
+ })
+
+ it('clears the error once a page succeeds', async () => {
+ const fetcher = jest.fn()
+ .mockRejectedValueOnce(timeout())
+ .mockResolvedValueOnce(page(0, 2))
+
+ const { result } = renderHook(() => useServerList<number>({ fetcher, pageSize: 2 }))
+ await waitFor(() => expect(result.current.error).toBeTruthy())
+
+ // Nothing loaded, so this retries page 0 and replaces rather than appending — the
+ // offset is still 0 and appending an empty list to an empty list is the same thing.
+ act(() => { result.current.retry() })
+
+ await waitFor(() => expect(result.current.items).toEqual([0, 1]))
+ expect(result.current.error).toBeNull()
+ })
+
+ it('prefers what the server said over the fallback', async () => {
+ const err: any = new Error('Request failed with status code 500')
+ err.response = { status: 500, data: { error: 'Database is locked' }, statusText: '', headers: {}, config: {} }
+ const fetcher = jest.fn().mockRejectedValue(err)
+
+ const { result } = renderHook(() =>
+ useServerList<number>({ fetcher, pageSize: 2, errorFallback: 'Never shown.' }))
+
+ await waitFor(() => expect(result.current.error).toBe('Database is locked'))
+ })
+})