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 save or delete says so, where the tap was (#177)

Carter5ec5f459dfc0
diff --git a/mobile/app/(tabs)/nutrition/[id].tsx b/mobile/app/(tabs)/nutrition/[id].tsx
index 726c5c3..9c3d536 100644
--- a/mobile/app/(tabs)/nutrition/[id].tsx
+++ b/mobile/app/(tabs)/nutrition/[id].tsx
@@ -2,7 +2,7 @@ import { useEffect, useState } from 'react'
import { Image, Pressable, ScrollView, Text, View } from 'react-native'
import { router, useLocalSearchParams } from 'expo-router'
import { AlertCircle, ArrowLeft, Edit2, Flame, Trash2 } from 'lucide-react-native'
-import { entryDay, type FoodLog, formatDay } from '@lyftr/shared'
+import { useAsyncAction, entryDay, type FoodLog, formatDay } from '@lyftr/shared'
import {
AppText, Card, ConfirmSheet, Loading, Screen, deleteConfirmProps,
} from '../../../src/components/ui'
@@ -24,7 +24,6 @@ export default function NutritionDetail() {
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
const [confirming, setConfirming] = useState(false)
- const [deleting, setDeleting] = useState(false)
const goBack = () => (router.canGoBack() ? router.back() : router.replace('/nutrition'))
@@ -35,17 +34,13 @@ export default function NutritionDetail() {
.finally(() => setLoading(false))
}, [id])
- const handleDelete = async () => {
- if (!entry || deleting) return
- setDeleting(true)
- try {
- await client.foodAPI.delete(entry.id)
- goBack() // the dashboard refetches on focus
- } catch {
- setDeleting(false)
- setConfirming(false)
- }
- }
+ // The catch here just closed up and left the screen unchanged, which is
+ // indistinguishable from a tap that never registered. It says why now.
+ const remove = useAsyncAction(async () => {
+ if (!entry) return
+ await client.foodAPI.delete(entry.id)
+ goBack() // the dashboard refetches on focus
+ }, 'Failed to delete entry')
if (loading) return <Loading />
@@ -114,9 +109,9 @@ export default function NutritionDetail() {
accessibilityRole="button"
accessibilityLabel="Delete entry"
onPress={() => setConfirming(true)}
- disabled={deleting}
+ disabled={remove.busy}
hitSlop={6}
- className={`h-9 w-9 items-center justify-center rounded-lg active:bg-error-500/10 ${deleting ? 'opacity-40' : ''}`}
+ className={`h-9 w-9 items-center justify-center rounded-lg active:bg-error-500/10 ${remove.busy ? 'opacity-40' : ''}`}
>
<Trash2 size={17} color={colors.txMuted} strokeWidth={2.2} />
</Pressable>
@@ -190,9 +185,10 @@ export default function NutritionDetail() {
<ConfirmSheet
{...deleteConfirmProps({ title: 'Delete entry?', subject: `"${entry.name}"` })}
open={confirming}
- busy={deleting}
- onConfirm={handleDelete}
- onCancel={() => setConfirming(false)}
+ busy={remove.busy}
+ error={remove.error}
+ onConfirm={() => { void remove.run() }}
+ onCancel={() => { setConfirming(false); remove.reset() }}
/>
</Screen>
)
diff --git a/mobile/app/(tabs)/nutrition/log.tsx b/mobile/app/(tabs)/nutrition/log.tsx
index e2193a2..da75849 100644
--- a/mobile/app/(tabs)/nutrition/log.tsx
+++ b/mobile/app/(tabs)/nutrition/log.tsx
@@ -6,7 +6,7 @@ import {
AlertCircle, ArrowLeft, ChevronRight, Minus, Plus, Scan, Star, Utensils, Zap,
} from 'lucide-react-native'
import {
- dayToInstant, entryDay, todayStr,
+ useAsyncAction, dayToInstant, entryDay, todayStr,
type FoodSearchResult, type SavedFood,
} from '@lyftr/shared'
import {
@@ -125,8 +125,6 @@ export default function LogFood() {
const isToggling = (item: FoodSearchResult) =>
togglingFavorite.has(`${item.name}|${item.brand ?? ''}`)
- const [saving, setSaving] = useState(false)
- const [saveError, setSaveError] = useState<string | null>(null)
const [favoriteError, setFavoriteError] = useState<string | null>(null)
const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null)
@@ -230,28 +228,25 @@ export default function LogFood() {
setServingsStr(String(next))
}
+ const save = useAsyncAction(async (item: FoodSearchResult) => {
+ const payload = {
+ ...scaleServing(item, servings),
+ meal,
+ logged_at: dayToInstant(date),
+ }
+ if (editId) {
+ await client.foodAPI.update(editId, payload)
+ } else {
+ await client.foodAPI.log(payload)
+ }
+ Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success).catch(() => {})
+ // Courier the confirmation to the dashboard toast: which meal (new) or 'Updated'.
+ router.replace(`/nutrition?logged=${editId ? 'Updated' : encodeURIComponent(MEAL_LABELS[meal])}`)
+ }, 'Failed to save')
+
const handleLog = async () => {
- if (!selected || saving) return
- setSaving(true)
- setSaveError(null)
- try {
- const payload = {
- ...scaleServing(selected, servings),
- meal,
- logged_at: dayToInstant(date),
- }
- if (editId) {
- await client.foodAPI.update(editId, payload)
- } else {
- await client.foodAPI.log(payload)
- }
- Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success).catch(() => {})
- // Courier the confirmation to the dashboard toast: which meal (new) or 'Updated'.
- router.replace(`/nutrition?logged=${editId ? 'Updated' : encodeURIComponent(MEAL_LABELS[meal])}`)
- } catch (err: any) {
- setSaveError(err?.response?.data?.error || 'Failed to save')
- setSaving(false)
- }
+ if (!selected || save.busy) return
+ void save.run(selected)
}
const goBack = () => {
@@ -457,10 +452,10 @@ export default function LogFood() {
<>
<ScrollView showsVerticalScrollIndicator={false} keyboardShouldPersistTaps="handled" contentContainerStyle={{ paddingBottom: 120 }}>
<View className="gap-4">
- {saveError ? (
+ {save.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">{saveError}</AppText>
+ <AppText variant="body" color="error" className="flex-1">{save.error}</AppText>
</View>
) : null}
@@ -581,10 +576,10 @@ export default function LogFood() {
{/* Sticky log button */}
<View className="border-t border-surface-border bg-surface-base pb-6 pt-3">
<Button
- title={saving ? 'Saving…' : editId ? 'Save Changes' : 'Log Food'}
+ title={save.busy ? 'Saving…' : editId ? 'Save Changes' : 'Log Food'}
onPress={handleLog}
- loading={saving}
- disabled={saving}
+ loading={save.busy}
+ disabled={save.busy}
/>
</View>
<NumericKeyboardAccessory />
diff --git a/mobile/app/(tabs)/programs/[id].tsx b/mobile/app/(tabs)/programs/[id].tsx
index 8aa2273..264ef71 100644
--- a/mobile/app/(tabs)/programs/[id].tsx
+++ b/mobile/app/(tabs)/programs/[id].tsx
@@ -6,7 +6,7 @@ import {
AlertCircle, ArrowLeft, Award, BookOpen, CalendarDays, Check, ChevronDown, ChevronRight, ChevronUp, Dumbbell,
Edit2, Layers, Moon, Pause, Play, TimerOff, TrendingUp, Trash2, X,
} from 'lucide-react-native'
-import {
+import { useAsyncAction,
activeSessionExercisesForDay, allExercises, apiErrorMessage, dayLabel, displayWeight, sessionNameForDay,
weightShort, type Program, type ProgramSet,
} from '@lyftr/shared'
@@ -76,7 +76,6 @@ export default function ProgramDetail() {
const [program, setProgram] = useState<Program | null>(null)
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
- const [deleting, setDeleting] = useState(false)
const [confirming, setConfirming] = useState(false)
const [resolving, setResolving] = useState(false)
const [showAllSuggestions, setShowAllSuggestions] = useState(false)
@@ -168,16 +167,13 @@ export default function ProgramDetail() {
router.navigate(activeHref)
}
- const handleDelete = async () => {
+ // The catch here just closed up and left the screen unchanged, which is
+ // indistinguishable from a tap that never registered. It says why now.
+ const remove = useAsyncAction(async () => {
if (!program) return
- setDeleting(true)
- try {
- await client.programAPI.delete(program.id)
- goBack() // list refetches on focus
- } catch {
- setDeleting(false)
- }
- }
+ await client.programAPI.delete(program.id)
+ goBack() // list refetches on focus
+ }, 'Failed to delete program')
if (loading) return <Loading />
@@ -275,9 +271,9 @@ export default function ProgramDetail() {
accessibilityRole="button"
accessibilityLabel="Delete program"
onPress={() => setConfirming(true)}
- disabled={deleting}
+ disabled={remove.busy}
hitSlop={6}
- className={`h-9 w-9 items-center justify-center rounded-lg active:bg-error-500/10 ${deleting ? 'opacity-40' : ''}`}
+ className={`h-9 w-9 items-center justify-center rounded-lg active:bg-error-500/10 ${remove.busy ? 'opacity-40' : ''}`}
>
<Trash2 size={17} color={colors.txMuted} strokeWidth={2.2} />
</Pressable>
@@ -287,9 +283,10 @@ export default function ProgramDetail() {
<ConfirmSheet
{...deleteConfirmProps({ title: 'Delete Program?', subject: `"${program.name}"` })}
open={confirming}
- busy={deleting}
- onConfirm={handleDelete}
- onCancel={() => setConfirming(false)}
+ busy={remove.busy}
+ error={remove.error}
+ onConfirm={() => { void remove.run() }}
+ onCancel={() => { setConfirming(false); remove.reset() }}
/>
{/* Auto-progression review banner (#40) — approve the targets you beat last workout */}
diff --git a/mobile/app/(tabs)/programs/[id]/edit.tsx b/mobile/app/(tabs)/programs/[id]/edit.tsx
index 9156295..82af72e 100644
--- a/mobile/app/(tabs)/programs/[id]/edit.tsx
+++ b/mobile/app/(tabs)/programs/[id]/edit.tsx
@@ -3,7 +3,7 @@ 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 { apiErrorMessage, displayToLbs, hasWorkoutExercises, lbsToDisplay, weightShort, type Exercise } from '@lyftr/shared'
+import { useAsyncAction, displayToLbs, hasWorkoutExercises, lbsToDisplay, weightShort, type Exercise } from '@lyftr/shared'
import { AppText, Button, Field, IconButton, Label, Loading, Screen } from '../../../../src/components/ui'
import { KeyboardDoneBar } from '../../../../src/components/workouts/KeyboardDoneBar'
import { ProgramDaysEditor } from '../../../../src/components/programs/ProgramDaysEditor'
@@ -36,8 +36,9 @@ export default function EditProgram() {
const wUnit = weightShort(settings.weight_unit)
const { brand, isDark } = useTheme()
- const [loading, setLoading] = useState(false)
const [initialLoading, setInitialLoading] = useState(true)
+ // 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('')
const [pickerExercises, setPickerExercises] = useState<Record<number, Exercise>>({})
const [formData, setFormData] = useState<ProgramFormData>({ name: '', notes: '', days: [] })
@@ -93,45 +94,43 @@ export default function EditProgram() {
const cacheExercise = (ex: Exercise) => setPickerExercises((prev) => ({ ...prev, [ex.id]: ex }))
+ const save = useAsyncAction(async () => {
+ const payload = {
+ name: formData.name,
+ notes: formData.notes,
+ // Declares this client round-trips day ids: without it, deleting every
+ // existing day and adding only new (id-less) ones is indistinguishable
+ // from a legacy payload and the server would positionally re-attribute
+ // the deleted days' workout history to the new days.
+ day_ids_known: true,
+ days: formData.days.map((d) => ({
+ id: d.id,
+ order_index: d.order_index,
+ is_rest_day: d.is_rest_day,
+ name: d.name,
+ exercises: d.exercises.map((ex) => ({
+ exercise_id: ex.exercise_id,
+ notes: ex.notes,
+ rest_seconds: ex.rest_seconds,
+ sets: ex.sets.map((s) => ({
+ set_number: s.set_number,
+ target_reps: s.reps,
+ target_weight: displayToLbs(s.weight, settings.weight_unit),
+ })),
+ })),
+ })),
+ }
+ await client.programAPI.update(Number(id), payload)
+ router.dismissTo('/programs')
+ }, 'Failed to update program')
+
const handleSubmit = async () => {
if (!formData.name.trim()) { setError('Program name required'); return }
if (formData.days.length === 0) { setError('Add at least one day'); return }
const hasAnyExercise = hasWorkoutExercises(formData.days)
if (!hasAnyExercise) { setError('Add at least one exercise to a workout day'); return }
- setLoading(true)
- try {
- const payload = {
- name: formData.name,
- notes: formData.notes,
- // Declares this client round-trips day ids: without it, deleting every
- // existing day and adding only new (id-less) ones is indistinguishable
- // from a legacy payload and the server would positionally re-attribute
- // the deleted days' workout history to the new days.
- day_ids_known: true,
- days: formData.days.map((d) => ({
- id: d.id,
- order_index: d.order_index,
- is_rest_day: d.is_rest_day,
- name: d.name,
- exercises: d.exercises.map((ex) => ({
- exercise_id: ex.exercise_id,
- notes: ex.notes,
- rest_seconds: ex.rest_seconds,
- sets: ex.sets.map((s) => ({
- set_number: s.set_number,
- target_reps: s.reps,
- target_weight: displayToLbs(s.weight, settings.weight_unit),
- })),
- })),
- })),
- }
- await client.programAPI.update(Number(id), payload)
- router.dismissTo('/programs')
- } catch (err) {
- setError(apiErrorMessage(err, 'Failed to update program'))
- } finally {
- setLoading(false)
- }
+ setError('')
+ void save.run()
}
if (initialLoading) return <Loading />
@@ -160,10 +159,10 @@ export default function EditProgram() {
</View>
</View>
- {error ? (
+ {error || save.error ? (
<View className="flex-row items-center gap-2 rounded-xl border border-error-500/20 bg-error-500/10 p-4">
<AlertCircle size={16} color={isDark ? brand.errorSoft : brand.error} />
- <AppText variant="body" color="error" className="flex-1">{error}</AppText>
+ <AppText variant="body" color="error" className="flex-1">{error || save.error}</AppText>
</View>
) : null}
@@ -206,7 +205,7 @@ export default function EditProgram() {
<View className="-mx-5 flex-row gap-3 border-t border-surface-border bg-surface-base px-5 pb-2 pt-3">
<Button title="Cancel" variant="secondary" className="flex-1" onPress={goBack} />
- <Button title="Save Changes" className="flex-1" onPress={handleSubmit} loading={loading} />
+ <Button title="Save Changes" className="flex-1" onPress={handleSubmit} loading={save.busy} />
</View>
<KeyboardDoneBar nativeID={KEYPAD_DONE_ID} />
diff --git a/mobile/app/(tabs)/programs/new.tsx b/mobile/app/(tabs)/programs/new.tsx
index f3db9f5..e6858a8 100644
--- a/mobile/app/(tabs)/programs/new.tsx
+++ b/mobile/app/(tabs)/programs/new.tsx
@@ -3,7 +3,7 @@ import { Platform, ScrollView, View } from 'react-native'
import { router } from 'expo-router'
import { AlertCircle, ArrowLeft, BookOpen, CalendarDays, FileText } from 'lucide-react-native'
import type { LucideIcon } from 'lucide-react-native'
-import { apiErrorMessage, displayToLbs, hasWorkoutExercises, weightShort, type Exercise } from '@lyftr/shared'
+import { useAsyncAction, displayToLbs, hasWorkoutExercises, weightShort, type Exercise } from '@lyftr/shared'
import { AppText, Button, Field, IconButton, Label, Screen } from '../../../src/components/ui'
import { KeyboardDoneBar } from '../../../src/components/workouts/KeyboardDoneBar'
import { ProgramDaysEditor } from '../../../src/components/programs/ProgramDaysEditor'
@@ -39,7 +39,8 @@ export default function AddProgram() {
const wUnit = weightShort(settings.weight_unit)
const { brand, isDark } = useTheme()
- const [loading, setLoading] = useState(false)
+ // 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('')
const [pickerExercises, setPickerExercises] = useState<Record<number, Exercise>>({})
const [formData, setFormData] = useState<ProgramFormData>({ name: '', notes: '', days: [] })
@@ -57,39 +58,37 @@ export default function AddProgram() {
const cacheExercise = (ex: Exercise) => setPickerExercises((prev) => ({ ...prev, [ex.id]: ex }))
+ const save = useAsyncAction(async () => {
+ const payload = {
+ name: formData.name,
+ notes: formData.notes,
+ days: formData.days.map((d) => ({
+ order_index: d.order_index,
+ is_rest_day: d.is_rest_day,
+ name: d.name,
+ exercises: d.exercises.map((ex) => ({
+ exercise_id: ex.exercise_id,
+ notes: ex.notes,
+ rest_seconds: ex.rest_seconds,
+ sets: ex.sets.map((s) => ({
+ set_number: s.set_number,
+ target_reps: s.reps,
+ target_weight: displayToLbs(s.weight, settings.weight_unit),
+ })),
+ })),
+ })),
+ }
+ await client.programAPI.create(payload)
+ router.dismissTo('/programs')
+ }, 'Failed to create program')
+
const handleSubmit = async () => {
if (!formData.name.trim()) { setError('Program name required'); return }
if (formData.days.length === 0) { setError('Add at least one day'); return }
const hasAnyExercise = hasWorkoutExercises(formData.days)
if (!hasAnyExercise) { setError('Add at least one exercise to a workout day'); return }
- setLoading(true)
- try {
- const payload = {
- name: formData.name,
- notes: formData.notes,
- days: formData.days.map((d) => ({
- order_index: d.order_index,
- is_rest_day: d.is_rest_day,
- name: d.name,
- exercises: d.exercises.map((ex) => ({
- exercise_id: ex.exercise_id,
- notes: ex.notes,
- rest_seconds: ex.rest_seconds,
- sets: ex.sets.map((s) => ({
- set_number: s.set_number,
- target_reps: s.reps,
- target_weight: displayToLbs(s.weight, settings.weight_unit),
- })),
- })),
- })),
- }
- await client.programAPI.create(payload)
- router.dismissTo('/programs')
- } catch (err) {
- setError(apiErrorMessage(err, 'Failed to create program'))
- } finally {
- setLoading(false)
- }
+ setError('')
+ void save.run()
}
const totalExercises = formData.days.reduce((s, d) => s + d.exercises.length, 0)
@@ -116,10 +115,10 @@ export default function AddProgram() {
</View>
</View>
- {error ? (
+ {error || save.error ? (
<View className="flex-row items-center gap-2 rounded-xl border border-error-500/20 bg-error-500/10 p-4">
<AlertCircle size={16} color={isDark ? brand.errorSoft : brand.error} />
- <AppText variant="body" color="error" className="flex-1">{error}</AppText>
+ <AppText variant="body" color="error" className="flex-1">{error || save.error}</AppText>
</View>
) : null}
@@ -163,7 +162,7 @@ export default function AddProgram() {
<View className="-mx-5 flex-row gap-3 border-t border-surface-border bg-surface-base px-5 pb-2 pt-3">
<Button title="Cancel" variant="secondary" className="flex-1" onPress={goBack} />
- <Button title="Save Program" className="flex-1" onPress={handleSubmit} loading={loading} />
+ <Button title="Save Program" className="flex-1" onPress={handleSubmit} loading={save.busy} />
</View>
<KeyboardDoneBar nativeID={KEYPAD_DONE_ID} />
diff --git a/mobile/app/(tabs)/settings/index.tsx b/mobile/app/(tabs)/settings/index.tsx
index 3721d67..0c0f046 100644
--- a/mobile/app/(tabs)/settings/index.tsx
+++ b/mobile/app/(tabs)/settings/index.tsx
@@ -18,7 +18,7 @@ import {
Timer,
Trash2,
} from 'lucide-react-native'
-import {
+import { useAsyncAction,
memberSince,
normalizeServerUrl,
testServerConnection,
@@ -72,7 +72,6 @@ export default function SettingsScreen() {
// Macro/calorie targets are the one batch-saved (server-side) block — mirror web:
// edit locally as text, PUT on "Save". Everything else writes on change.
const [targets, setTargets] = useState({ calorie_target: '', protein_target: '', carb_target: '', fat_target: '' })
- const [saving, setSaving] = useState(false)
const [showCustomRest, setShowCustomRest] = useState(false)
@@ -83,7 +82,6 @@ export default function SettingsScreen() {
const [testing, setTesting] = useState(false)
const [confirmDelete, setConfirmDelete] = useState(false)
- const [deleting, setDeleting] = useState(false)
useEffect(() => {
fetchSettings()
@@ -112,22 +110,17 @@ export default function SettingsScreen() {
const onDigits = (key: keyof typeof targets) => (t: string) =>
setTargets((p) => ({ ...p, [key]: sanitizeNumericInput(t, 'numeric') }))
- const handleSaveTargets = async () => {
- setSaving(true)
- try {
- await updateSettings({
- calorie_target: parseInt(targets.calorie_target) || 0,
- protein_target: parseInt(targets.protein_target) || 0,
- carb_target: parseInt(targets.carb_target) || 0,
- fat_target: parseInt(targets.fat_target) || 0,
- })
- setToast({ variant: 'success', title: 'Targets saved' })
- } catch (err: any) {
- setToast({ variant: 'error', title: 'Could not save targets', description: err?.message })
- } finally {
- setSaving(false)
- }
- }
+ const saveTargets = useAsyncAction(async () => {
+ await updateSettings({
+ calorie_target: parseInt(targets.calorie_target) || 0,
+ protein_target: parseInt(targets.protein_target) || 0,
+ carb_target: parseInt(targets.carb_target) || 0,
+ fat_target: parseInt(targets.fat_target) || 0,
+ })
+ setToast({ variant: 'success', title: 'Targets saved' })
+ }, 'Could not save targets')
+
+ const handleSaveTargets = () => { void saveTargets.run() }
const saveServer = async () => {
setTesting(true)
@@ -145,19 +138,26 @@ export default function SettingsScreen() {
setTesting(false)
}
- const handleDeleteAccount = async () => {
- setDeleting(true)
- try {
- await client.userAPI.deleteAccount()
- // logout flips isAuthenticated; the root layout's Stack.Protected guard then makes
- // (tabs) unreachable and expo-router moves the user to sign-in. Nothing routes by hand.
- await logout()
- } catch (err: any) {
- setDeleting(false)
+ const deleteAccount = useAsyncAction(async () => {
+ await client.userAPI.deleteAccount()
+ // logout flips isAuthenticated; the root layout's Stack.Protected guard then makes
+ // (tabs) unreachable and expo-router moves the user to sign-in. Nothing routes by hand.
+ await logout()
+ }, 'Could not delete account')
+
+ // These two report through the toast rather than an inline alert, so the message is
+ // read off the hook when it changes. It used to be `err?.message`, which for an axios
+ // error is the string "Request failed with status code 400" - true, and useless.
+ useEffect(() => {
+ if (saveTargets.error) setToast({ variant: 'error', title: 'Could not save targets', description: saveTargets.error })
+ }, [saveTargets.error])
+
+ useEffect(() => {
+ if (deleteAccount.error) {
setConfirmDelete(false)
- setToast({ variant: 'error', title: 'Could not delete account', description: err?.message })
+ setToast({ variant: 'error', title: 'Could not delete account', description: deleteAccount.error })
}
- }
+ }, [deleteAccount.error])
if (!loaded) return <Loading />
@@ -337,7 +337,7 @@ export default function SettingsScreen() {
onChangeText={onDigits('fat_target')}
rightSlot={<Muted className="text-xs">g</Muted>}
/>
- <Button title="Save targets" onPress={handleSaveTargets} loading={saving} className="mt-1" />
+ <Button title="Save targets" onPress={handleSaveTargets} loading={saveTargets.busy} className="mt-1" />
</View>
</SettingsGroup>
@@ -413,8 +413,8 @@ export default function SettingsScreen() {
message="This permanently deletes your account and all of your data. This can't be undone."
confirmLabel="Delete account"
busyLabel="Deleting…"
- busy={deleting}
- onConfirm={handleDeleteAccount}
+ busy={deleteAccount.busy}
+ onConfirm={() => { void deleteAccount.run() }}
onCancel={() => setConfirmDelete(false)}
/>
</Screen>
diff --git a/mobile/app/(tabs)/settings/password.tsx b/mobile/app/(tabs)/settings/password.tsx
index 1e0b4ad..109949b 100644
--- a/mobile/app/(tabs)/settings/password.tsx
+++ b/mobile/app/(tabs)/settings/password.tsx
@@ -2,7 +2,7 @@ import { useState } from 'react'
import { Pressable, ScrollView, View } from 'react-native'
import { router } from 'expo-router'
import { ArrowLeft, ShieldCheck } from 'lucide-react-native'
-import { apiErrorMessage, differentRuleLabel, lengthRuleLabel, matchRuleLabel, newPasswordRules } from '@lyftr/shared'
+import { useAsyncAction, differentRuleLabel, lengthRuleLabel, matchRuleLabel, newPasswordRules } from '@lyftr/shared'
import {
Alert,
AppText,
@@ -30,33 +30,27 @@ export default function ChangePasswordScreen() {
const [current, setCurrent] = useState('')
const [next, setNext] = useState('')
const [confirm, setConfirm] = useState('')
- const [saving, setSaving] = useState(false)
- const [error, setError] = useState<string | null>(null)
const [done, setDone] = useState(false)
const rules = newPasswordRules({ password: next, confirm, current })
const back = () => (router.canGoBack() ? router.back() : router.navigate('/settings'))
+ const save = useAsyncAction(async () => {
+ // The shared client persists the returned token pair, so this device stays signed
+ // in while every other one is evicted.
+ await client.userAPI.changePassword({ current_password: current, new_password: next })
+ setCurrent(''); setNext(''); setConfirm('')
+ setDone(true)
+ }, "Couldn't change your password. Please try again.")
+
const submit = async () => {
- setError(null)
// The rules render under the fields as the user types and the button stays disabled
// until they pass, so this is a backstop. The alert below is server failures only —
// a wrong current password, or a change that landed elsewhere first.
if (!rules.ready) return
- setSaving(true)
- try {
- // The shared client persists the returned token pair, so this device stays signed
- // in while every other one is evicted.
- await client.userAPI.changePassword({ current_password: current, new_password: next })
- setCurrent(''); setNext(''); setConfirm('')
- setDone(true)
- } catch (err: any) {
- setError(apiErrorMessage(err, "Couldn't change your password. Please try again."))
- } finally {
- setSaving(false)
- }
+ void save.run()
}
const backLink = (
@@ -139,13 +133,13 @@ export default function ChangePasswordScreen() {
{/* Form-level, so it belongs beside the action it blocked rather than hanging
off one field — pinning it to the confirm box pointed the user at the wrong
input for an error about the current password. */}
- {error ? <Alert variant="error">{error}</Alert> : null}
+ {save.error ? <Alert variant="error">{save.error}</Alert> : null}
<View className="flex-row gap-2">
<Button
title="Update password"
onPress={submit}
- loading={saving}
+ loading={save.busy}
disabled={!rules.ready}
className="flex-1"
/>
@@ -153,7 +147,7 @@ export default function ChangePasswordScreen() {
title="Cancel"
variant="secondary"
onPress={back}
- disabled={saving}
+ disabled={save.busy}
className="flex-1"
/>
</View>
diff --git a/mobile/app/(tabs)/weight/[id].tsx b/mobile/app/(tabs)/weight/[id].tsx
index 1388262..a9c3f82 100644
--- a/mobile/app/(tabs)/weight/[id].tsx
+++ b/mobile/app/(tabs)/weight/[id].tsx
@@ -3,7 +3,7 @@ import { Pressable, ScrollView, Text, View } from 'react-native'
import { router, useLocalSearchParams } from 'expo-router'
import * as Haptics from 'expo-haptics'
import { AlertCircle, ArrowLeft, Edit2, Scale, Trash2 } from 'lucide-react-native'
-import { apiErrorMessage, dayToInstant, displayWeight, maxWeight, resolveWeightLbs, weightError, weightShort, type WeightLog, entryDay, BODYWEIGHT_STEP, clampStep, formatDay } from '@lyftr/shared'
+import { useAsyncAction, apiErrorMessage, dayToInstant, displayWeight, maxWeight, resolveWeightLbs, weightError, weightShort, type WeightLog, entryDay, BODYWEIGHT_STEP, clampStep, formatDay } from '@lyftr/shared'
import {
AppText, Button, Card, ConfirmSheet, DateInput, Field, Label, Loading, NumberField,
NumericKeyboardAccessory, NUMERIC_ACCESSORY_ID, Screen, StepperTile, deleteConfirmProps,
@@ -27,12 +27,10 @@ export default function WeightDetail() {
const [editWeight, setEditWeight] = useState('')
const [editDate, setEditDate] = useState('')
const [editNotes, setEditNotes] = useState('')
- const [saving, setSaving] = useState(false)
const [editError, setEditError] = useState('')
// Delete confirm
const [confirming, setConfirming] = useState(false)
- const [deleting, setDeleting] = useState(false)
const goBack = () => (router.canGoBack() ? router.back() : router.replace('/weight'))
@@ -60,45 +58,41 @@ export default function WeightDetail() {
setEditing(true)
}
- const handleSave = async () => {
- if (!log || saving) return
+ const saveEdit = useAsyncAction(async (entry: WeightLog) => {
+ const updated = await client.weightAPI.update(entry.id, {
+ // resolveWeightLbs keeps the original lbs when the shown 0.1 value is unchanged
+ // (avoids kg round-trip drift); only converts when the user actually edited it.
+ weight: resolveWeightLbs(editWeight, entry.weight, unit),
+ notes: editNotes.trim(),
+ logged_at: dayToInstant(editDate, entry.logged_at),
+ })
+ Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success).catch(() => {})
+ setLog(updated)
+ setEditing(false)
+ }, 'Failed to save')
+
+ // `editError` is what this screen can say about the value in the box; the hook carries
+ // what the server said. The entry is passed to run() because the guard above is what
+ // proves it is not null.
+ const handleSave = () => {
+ if (!log || saveEdit.busy) return
const w = parseFloat(editWeight)
const wErr = weightError(w, unit)
if (wErr) {
setEditError(wErr)
return
}
- setSaving(true)
setEditError('')
- try {
- const updated = await client.weightAPI.update(log.id, {
- // resolveWeightLbs keeps the original lbs when the shown 0.1 value is unchanged
- // (avoids kg round-trip drift); only converts when the user actually edited it.
- weight: resolveWeightLbs(editWeight, log.weight, unit),
- notes: editNotes.trim(),
- logged_at: dayToInstant(editDate, log.logged_at),
- })
- Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success).catch(() => {})
- setLog(updated)
- setEditing(false)
- } catch (err) {
- setEditError(apiErrorMessage(err, 'Failed to save'))
- } finally {
- setSaving(false)
- }
+ void saveEdit.run(log)
}
- const handleDelete = async () => {
- if (!log || deleting) return
- setDeleting(true)
- try {
- await client.weightAPI.delete(log.id)
- goBack() // the list refetches on focus
- } catch {
- setDeleting(false)
- setConfirming(false)
- }
- }
+ // The catch here just closed up and left the screen unchanged, which is
+ // indistinguishable from a tap that never registered. It says why now.
+ const remove = useAsyncAction(async () => {
+ if (!log) return
+ await client.weightAPI.delete(log.id)
+ goBack() // the list refetches on focus
+ }, 'Failed to delete entry')
if (loading) return <Loading />
@@ -145,9 +139,9 @@ export default function WeightDetail() {
accessibilityRole="button"
accessibilityLabel="Delete entry"
onPress={() => setConfirming(true)}
- disabled={deleting}
+ disabled={remove.busy}
hitSlop={6}
- className={`h-9 w-9 items-center justify-center rounded-lg active:bg-error-500/10 ${deleting ? 'opacity-40' : ''}`}
+ className={`h-9 w-9 items-center justify-center rounded-lg active:bg-error-500/10 ${remove.busy ? 'opacity-40' : ''}`}
>
<Trash2 size={17} color={colors.txMuted} strokeWidth={2.2} />
</Pressable>
@@ -188,10 +182,10 @@ export default function WeightDetail() {
<Card>
<AppText variant="heading" className="mb-4">Edit Entry</AppText>
<View className="gap-4">
- {editError ? (
+ {editError || saveEdit.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={16} color={brand.errorSoft} />
- <Text className="flex-1 font-sans text-sm text-error-400">{editError}</Text>
+ <Text className="flex-1 font-sans text-sm text-error-400">{editError || saveEdit.error}</Text>
</View>
) : null}
@@ -227,7 +221,7 @@ export default function WeightDetail() {
<Button title="Cancel" variant="secondary" onPress={() => { setEditing(false); setEditError('') }} />
</View>
<View className="flex-1">
- <Button title={saving ? 'Saving…' : 'Save'} onPress={handleSave} loading={saving} disabled={!(parseFloat(editWeight) > 0) || saving} />
+ <Button title={saveEdit.busy ? 'Saving…' : 'Save'} onPress={handleSave} loading={saveEdit.busy} disabled={!(parseFloat(editWeight) > 0) || saveEdit.busy} />
</View>
</View>
</View>
@@ -242,9 +236,10 @@ export default function WeightDetail() {
subject: `${formatDay(entryDay(log), 'MMMM d, yyyy')} · ${displayWeight(log.weight, unit)} ${wUnit}`,
})}
open={confirming}
- busy={deleting}
- onConfirm={handleDelete}
- onCancel={() => setConfirming(false)}
+ busy={remove.busy}
+ error={remove.error}
+ onConfirm={() => { void remove.run() }}
+ onCancel={() => { setConfirming(false); remove.reset() }}
/>
{/* iOS Done bar above the numeric keyboard (the edit weight NumberField links it). */}
<NumericKeyboardAccessory />
diff --git a/mobile/app/(tabs)/weight/index.tsx b/mobile/app/(tabs)/weight/index.tsx
index f4c5604..abda641 100644
--- a/mobile/app/(tabs)/weight/index.tsx
+++ b/mobile/app/(tabs)/weight/index.tsx
@@ -7,7 +7,7 @@ import {
Activity, AlertCircle, ArrowDown, ArrowUp, Calendar, Minus, Scale, Sunrise,
TrendingDown, TrendingUp, X,
} from 'lucide-react-native'
-import { apiErrorMessage, dayToInstant, daysAgoStr, displayToLbs, displayWeight, maxWeight, todayStr, weightError, weightShort, type WeightLog, type WeightStats, entryDay, dayToLocalDate, BODYWEIGHT_STEP, clampStep, formatDay } from '@lyftr/shared'
+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 {
AppText, Button, Card, DateInput, Field, Label, NumberField, NumericKeyboardAccessory,
NUMERIC_ACCESSORY_ID, PageHeader, Screen, SegmentedControl, StepperTile,
@@ -70,7 +70,6 @@ export default function Weight() {
const [newWeight, setNewWeight] = useState('')
const [newDate, setNewDate] = useState(todayStr())
const [newNotes, setNewNotes] = useState('')
- const [logging, setLogging] = useState(false)
const [showNotes, setShowNotes] = useState(false)
const [showDuplicateWarning, setShowDuplicateWarning] = useState(false)
const duplicateWarningDismissedRef = useRef(false)
@@ -112,8 +111,25 @@ export default function Weight() {
)
const [chartWidth, setChartWidth] = useState(0)
+ const log = useAsyncAction(async (w: number) => {
+ const real = await client.weightAPI.log({
+ weight: displayToLbs(w, unit),
+ notes: newNotes.trim(),
+ logged_at: dayToInstant(newDate),
+ })
+ Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success).catch(() => {})
+ setNewWeight(String(displayWeight(real.weight, unit)))
+ setNewNotes('')
+ setNewDate(todayStr())
+ setShowNotes(false)
+ duplicateWarningDismissedRef.current = false
+ reload()
+ refetchStats()
+ refetchChart()
+ }, 'Failed to log weight')
+
const handleLog = async () => {
- if (logging) return
+ if (log.busy) return
const w = parseFloat(newWeight)
const wErr = weightError(w, unit)
if (wErr) {
@@ -127,30 +143,9 @@ export default function Weight() {
return
}
- setLogging(true)
setError(null)
setShowDuplicateWarning(false)
-
- try {
- const real = await client.weightAPI.log({
- weight: displayToLbs(w, unit),
- notes: newNotes.trim(),
- logged_at: dayToInstant(newDate),
- })
- Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success).catch(() => {})
- setNewWeight(String(displayWeight(real.weight, unit)))
- setNewNotes('')
- setNewDate(todayStr())
- setShowNotes(false)
- duplicateWarningDismissedRef.current = false
- reload()
- refetchStats()
- refetchChart()
- } catch (err) {
- setError(apiErrorMessage(err, 'Failed to log weight'))
- } finally {
- setLogging(false)
- }
+ void log.run(w)
}
if (initialLoading) return <WeightSkeleton />
@@ -220,10 +215,10 @@ export default function Weight() {
}
/>
- {error ? (
+ {error || log.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={brand.errorSoft} />
- <Text className="flex-1 font-sans text-sm text-error-400">{error}</Text>
+ <Text className="flex-1 font-sans text-sm text-error-400">{error || log.error}</Text>
</View>
) : null}
@@ -315,10 +310,10 @@ export default function Weight() {
) : null}
<Button
- title={logging ? 'Logging…' : 'Log Weight'}
+ title={log.busy ? 'Logging…' : 'Log Weight'}
onPress={handleLog}
- loading={logging}
- disabled={!(parseFloat(newWeight) > 0) || logging}
+ loading={log.busy}
+ disabled={!(parseFloat(newWeight) > 0) || log.busy}
/>
<View className="flex-row items-center justify-center gap-1.5">
<Sunrise size={14} color={brand.warningSoft} />
diff --git a/mobile/app/(tabs)/workouts/[id].tsx b/mobile/app/(tabs)/workouts/[id].tsx
index 5b64950..a820e92 100644
--- a/mobile/app/(tabs)/workouts/[id].tsx
+++ b/mobile/app/(tabs)/workouts/[id].tsx
@@ -4,7 +4,7 @@ import { router, useLocalSearchParams, type Href } from 'expo-router'
import {
AlertCircle, ArrowLeft, ChevronRight, Clock, Edit2, Layers, Pause, TimerOff, Trash2, TrendingUp,
} from 'lucide-react-native'
-import { apiErrorMessage, displayVolume, displayWeight, weightShort, type Workout, type Set as WorkoutSet, workoutDay, restLabel, calcVolume, countWorkingSets, exerciseVolume, formatDay } from '@lyftr/shared'
+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 { ExerciseImage } from '../../../src/components/workouts/ExerciseImage'
import { client, useSettingsStore } from '../../../src/lib/lyftr'
@@ -59,7 +59,6 @@ export default function WorkoutDetail() {
const [workout, setWorkout] = useState<Workout | null>(null)
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
- const [deleting, setDeleting] = useState(false)
const [confirming, setConfirming] = useState(false)
useEffect(() => {
@@ -87,16 +86,13 @@ export default function WorkoutDetail() {
// Web's portal bottom-sheet confirm, ported 1:1 to a slide-up ConfirmSheet
// (replaces the interim OS Alert) — closer to the web app the user knows.
- const handleDelete = async () => {
+ // The catch here just closed up and left the screen unchanged, which is
+ // indistinguishable from a tap that never registered. It says why now.
+ const remove = useAsyncAction(async () => {
if (!workout) return
- setDeleting(true)
- try {
- await client.workoutAPI.delete(workout.id)
- goBack() // list refetches on focus
- } catch {
- setDeleting(false)
- }
- }
+ await client.workoutAPI.delete(workout.id)
+ goBack() // list refetches on focus
+ }, 'Failed to delete workout')
if (loading) return <Loading />
@@ -155,9 +151,9 @@ export default function WorkoutDetail() {
accessibilityRole="button"
accessibilityLabel="Delete workout"
onPress={() => setConfirming(true)}
- disabled={deleting}
+ disabled={remove.busy}
hitSlop={6}
- className={`h-9 w-9 items-center justify-center rounded-lg active:bg-error-500/10 ${deleting ? 'opacity-40' : ''}`}
+ className={`h-9 w-9 items-center justify-center rounded-lg active:bg-error-500/10 ${remove.busy ? 'opacity-40' : ''}`}
>
<Trash2 size={17} color={colors.txMuted} strokeWidth={2.2} />
</Pressable>
@@ -168,9 +164,10 @@ export default function WorkoutDetail() {
<ConfirmSheet
{...deleteConfirmProps({ title: 'Delete Workout?', subject: `"${workout.name}"` })}
open={confirming}
- busy={deleting}
- onConfirm={handleDelete}
- onCancel={() => setConfirming(false)}
+ busy={remove.busy}
+ error={remove.error}
+ onConfirm={() => { void remove.run() }}
+ onCancel={() => { setConfirming(false); remove.reset() }}
/>
{/* Header card */}
diff --git a/mobile/app/(tabs)/workouts/[id]/edit.tsx b/mobile/app/(tabs)/workouts/[id]/edit.tsx
index eaec99b..0b21c44 100644
--- a/mobile/app/(tabs)/workouts/[id]/edit.tsx
+++ b/mobile/app/(tabs)/workouts/[id]/edit.tsx
@@ -5,7 +5,7 @@ import {
AlertCircle, ArrowLeft, CalendarDays, Clock, Dumbbell, FileText, Plus, Zap,
} from 'lucide-react-native'
import type { LucideIcon } from 'lucide-react-native'
-import { apiErrorMessage, dayToInstant, displayToLbs, lbsToDisplay, weightShort, type Exercise, workoutDay } from '@lyftr/shared'
+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 { ExerciseFormCard } from '../../../../src/components/workouts/ExerciseFormCard'
import { DurationField } from '../../../../src/components/workouts/DurationField'
@@ -58,8 +58,9 @@ export default function EditWorkout() {
const { brand, accent, isDark } = useTheme()
const [showPicker, setShowPicker] = useState(false)
- const [loading, setLoading] = useState(false)
const [initialLoading, setInitialLoading] = useState(true)
+ // 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('')
const [pickerExercises, setPickerExercises] = useState<Record<number, Exercise>>({})
const [formData, setFormData] = useState<WorkoutFormData>({ name: '', notes: '', date: '', duration: 0, exercises: [] })
@@ -182,32 +183,30 @@ export default function EditWorkout() {
}))
}, [])
+ const save = useAsyncAction(async () => {
+ const payload = {
+ ...formData,
+ duration: formData.duration * 60,
+ // Move only the day; keep the logged time-of-day from the original timestamp.
+ started_at: formData.date
+ ? dayToInstant(formData.date, originalStartedAt || undefined)
+ : originalStartedAt || new Date().toISOString(),
+ exercises: formData.exercises.map((ex) => ({
+ ...ex,
+ sets: ex.sets.map((s) => ({ ...s, weight: displayToLbs(s.weight, settings.weight_unit) })),
+ })),
+ }
+ await client.workoutAPI.update(Number(id), payload)
+ // Web navigates to /workouts. Pop past the (stale) detail screen back to the
+ // list — the detail refetches on next visit; the list reloads on focus.
+ router.dismissTo('/workouts')
+ }, 'Failed to update workout')
+
const handleSubmit = async () => {
if (!formData.name.trim()) { setError('Workout name required'); return }
if (formData.exercises.length === 0) { setError('Add at least one exercise'); return }
- setLoading(true)
- try {
- const payload = {
- ...formData,
- duration: formData.duration * 60,
- // Move only the day; keep the logged time-of-day from the original timestamp.
- started_at: formData.date
- ? dayToInstant(formData.date, originalStartedAt || undefined)
- : originalStartedAt || new Date().toISOString(),
- exercises: formData.exercises.map((ex) => ({
- ...ex,
- sets: ex.sets.map((s) => ({ ...s, weight: displayToLbs(s.weight, settings.weight_unit) })),
- })),
- }
- await client.workoutAPI.update(Number(id), payload)
- // Web navigates to /workouts. Pop past the (stale) detail screen back to the
- // list — the detail refetches on next visit; the list reloads on focus.
- router.dismissTo('/workouts')
- } catch (err) {
- setError(apiErrorMessage(err, 'Failed to update workout'))
- } finally {
- setLoading(false)
- }
+ setError('')
+ void save.run()
}
if (initialLoading) return <Loading />
@@ -244,10 +243,10 @@ export default function EditWorkout() {
</View>
</View>
- {error ? (
+ {error || save.error ? (
<View className="flex-row items-center gap-2 rounded-xl border border-error-500/20 bg-error-500/10 p-4">
<AlertCircle size={16} color={isDark ? brand.errorSoft : brand.error} />
- <AppText variant="body" color="error" className="flex-1">{error}</AppText>
+ <AppText variant="body" color="error" className="flex-1">{error || save.error}</AppText>
</View>
) : null}
@@ -361,7 +360,7 @@ export default function EditWorkout() {
-mx-5 lets the divider span edge-to-edge past Screen's px-5. */}
<View className="-mx-5 flex-row gap-3 border-t border-surface-border bg-surface-base px-5 pb-2 pt-3">
<Button title="Cancel" variant="secondary" className="flex-1" onPress={goBack} />
- <Button title="Save Changes" className="flex-1" onPress={handleSubmit} loading={loading} />
+ <Button title="Save Changes" className="flex-1" onPress={handleSubmit} loading={save.busy} />
</View>
{/* iOS-only Done bar docked above the numeric keypads (they have no return key). */}
diff --git a/mobile/app/(tabs)/workouts/active.tsx b/mobile/app/(tabs)/workouts/active.tsx
index f857548..0d299d8 100644
--- a/mobile/app/(tabs)/workouts/active.tsx
+++ b/mobile/app/(tabs)/workouts/active.tsx
@@ -3,7 +3,7 @@ import { Keyboard, Pressable, ScrollView, Text, View } from 'react-native'
import * as Haptics from 'expo-haptics'
import { router } from 'expo-router'
import { CheckCircle2, Dumbbell, Flag, Plus, Timer, X } from 'lucide-react-native'
-import { apiErrorMessage, weightShort, type Exercise, formatElapsed, useElapsedSeconds } from '@lyftr/shared'
+import { useAsyncAction, weightShort, type Exercise, formatElapsed, useElapsedSeconds } from '@lyftr/shared'
import { AppText, ConfirmSheet, NumericKeyboardAccessory, Screen } from '../../../src/components/ui'
import { ActiveExerciseCard } from '../../../src/components/workouts/ActiveExerciseCard'
import { ExercisePicker } from '../../../src/components/workouts/ExercisePicker'
@@ -35,8 +35,6 @@ export default function ActiveWorkout() {
const elapsed = useElapsedSeconds(session?.started_at)
const [confirmCancel, setConfirmCancel] = useState(false)
const [confirmFinish, setConfirmFinish] = useState(false)
- const [saveError, setSaveError] = useState('')
- const [saving, setSaving] = useState(false)
const [activeExIdx, setActiveExIdx] = useState(0)
const [showPicker, setShowPicker] = useState(false)
@@ -55,24 +53,16 @@ export default function ActiveWorkout() {
const goHome = () => router.replace('/workouts')
- const handleFinish = async () => {
- setSaving(true)
- setSaveError('')
- try {
- const created = await client.workoutAPI.create(buildPayload())
- setOutcome({ kind: 'saved', workoutId: created.id, progression: created.progression })
- cancelSession()
- router.replace('/workouts')
- } catch (err: any) {
- // apiErrorMessage, not err.response.data.error: the failure this path exists for
- // has no response at all (#145 - the request timed out on gym wifi), and the raw
- // read would fall through to a generic string that says nothing about why.
- setSaveError(apiErrorMessage(err, 'Failed to save workout'))
- setSaving(false)
- // Sheet stays OPEN. The session is intact and the server may be reachable again
- // in a moment, so the retry belongs under the finger that just tapped Finish.
- }
- }
+ // The sheet stays OPEN when this fails. The session is intact and the server may
+ // be reachable again in a moment, so the retry belongs under the finger that just
+ // tapped Finish - the alternative, dismissing to a banner at the top of a scrolled
+ // list, is what #145 felt like from the user's seat.
+ const finish = useAsyncAction(async () => {
+ const created = await client.workoutAPI.create(buildPayload())
+ setOutcome({ kind: 'saved', workoutId: created.id, progression: created.progression })
+ cancelSession()
+ router.replace('/workouts')
+ }, 'Failed to save workout')
const jumpToExercise = useCallback((idx: number) => {
setActiveExIdx(idx)
@@ -255,10 +245,10 @@ export default function ActiveWorkout() {
confirmLabel="Finish"
busyLabel="Saving…"
cancelLabel="Keep Going"
- busy={saving}
- error={saveError}
- onConfirm={handleFinish}
- onCancel={() => { setConfirmFinish(false); setSaveError('') }}
+ busy={finish.busy}
+ error={finish.error}
+ onConfirm={() => { void finish.run() }}
+ onCancel={() => { setConfirmFinish(false); finish.reset() }}
/>
{/* Cancel confirm */}
diff --git a/mobile/app/(tabs)/workouts/new.tsx b/mobile/app/(tabs)/workouts/new.tsx
index 2e6a206..9259d4a 100644
--- a/mobile/app/(tabs)/workouts/new.tsx
+++ b/mobile/app/(tabs)/workouts/new.tsx
@@ -5,7 +5,7 @@ import {
AlertCircle, ArrowLeft, BookOpen, CalendarDays, Clock, Dumbbell, FileText, Plus, Zap,
} from 'lucide-react-native'
import type { LucideIcon } from 'lucide-react-native'
-import { apiErrorMessage, displayToLbs, lbsToDisplay, weightShort, type Exercise, type Program, type ProgramDay, dayToInstant, todayStr } from '@lyftr/shared'
+import { useAsyncAction, displayToLbs, lbsToDisplay, weightShort, type Exercise, type Program, type ProgramDay, dayToInstant, todayStr } from '@lyftr/shared'
import { AppText, Button, DateInput, EmptyState, Field, IconButton, Label, Screen } from '../../../src/components/ui'
import { ExerciseFormCard } from '../../../src/components/workouts/ExerciseFormCard'
import { DurationField } from '../../../src/components/workouts/DurationField'
@@ -56,7 +56,8 @@ export default function AddWorkout() {
const [showPicker, setShowPicker] = useState(false)
const [showProgramPicker, setShowProgramPicker] = useState(false)
- const [loading, setLoading] = useState(false)
+ // 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('')
const [pickerExercises, setPickerExercises] = useState<Record<number, Exercise>>({})
const [formData, setFormData] = useState<WorkoutFormData>({
@@ -164,29 +165,27 @@ export default function AddWorkout() {
}))
}, [])
+ const save = useAsyncAction(async () => {
+ // Exact web payload (the spread leaks `date` — backend ignores it; keep it).
+ const payload = {
+ ...formData,
+ duration: formData.duration * 60,
+ started_at: dayToInstant(formData.date),
+ exercises: formData.exercises.map((ex) => ({
+ ...ex,
+ sets: ex.sets.map((s) => ({ ...s, weight: displayToLbs(s.weight, settings.weight_unit) })),
+ })),
+ }
+ await client.workoutAPI.create(payload)
+ // Web navigates to /workouts; pop back to the list (it reloads on focus).
+ router.dismissTo('/workouts')
+ }, 'Failed to create workout')
+
const handleSubmit = async () => {
if (!formData.name.trim()) { setError('Workout name required'); return }
if (formData.exercises.length === 0) { setError('Add at least one exercise'); return }
- setLoading(true)
- try {
- // Exact web payload (the spread leaks `date` — backend ignores it; keep it).
- const payload = {
- ...formData,
- duration: formData.duration * 60,
- started_at: dayToInstant(formData.date),
- exercises: formData.exercises.map((ex) => ({
- ...ex,
- sets: ex.sets.map((s) => ({ ...s, weight: displayToLbs(s.weight, settings.weight_unit) })),
- })),
- }
- await client.workoutAPI.create(payload)
- // Web navigates to /workouts; pop back to the list (it reloads on focus).
- router.dismissTo('/workouts')
- } catch (err) {
- setError(apiErrorMessage(err, 'Failed to create workout'))
- } finally {
- setLoading(false)
- }
+ setError('')
+ void save.run()
}
const selectedIds = formData.exercises.map((e) => e.exercise_id)
@@ -222,10 +221,10 @@ export default function AddWorkout() {
</View>
{/* Form/request error — boxed alert (authui AuthError pattern) */}
- {error ? (
+ {error || save.error ? (
<View className="flex-row items-center gap-2 rounded-xl border border-error-500/20 bg-error-500/10 p-4">
<AlertCircle size={16} color={isDark ? brand.errorSoft : brand.error} />
- <AppText variant="body" color="error" className="flex-1">{error}</AppText>
+ <AppText variant="body" color="error" className="flex-1">{error || save.error}</AppText>
</View>
) : null}
@@ -358,7 +357,7 @@ export default function AddWorkout() {
-mx-5 lets the divider span edge-to-edge past Screen's px-5. */}
<View className="-mx-5 flex-row gap-3 border-t border-surface-border bg-surface-base px-5 pb-2 pt-3">
<Button title="Cancel" variant="secondary" className="flex-1" onPress={goBack} />
- <Button title="Save Workout" className="flex-1" onPress={handleSubmit} loading={loading} />
+ <Button title="Save Workout" className="flex-1" onPress={handleSubmit} loading={save.busy} />
</View>
{/* iOS-only Done bar docked above the numeric keypads (they have no return key). */}
diff --git a/mobile/src/components/dashboard/QuickWeighInSheet.tsx b/mobile/src/components/dashboard/QuickWeighInSheet.tsx
index 39ad27c..e0850b1 100644
--- a/mobile/src/components/dashboard/QuickWeighInSheet.tsx
+++ b/mobile/src/components/dashboard/QuickWeighInSheet.tsx
@@ -2,7 +2,7 @@ import { useEffect, useState } from 'react'
import { Pressable, Text, View } from 'react-native'
import * as Haptics from 'expo-haptics'
import { AlertCircle, Scale, X } from 'lucide-react-native'
-import { apiErrorMessage, dayToInstant, displayToLbs, maxWeight, todayStr, weightError, weightShort, type WeightLog, entryDay, BODYWEIGHT_STEP, clampStep } from '@lyftr/shared'
+import { useAsyncAction, dayToInstant, displayToLbs, maxWeight, todayStr, weightError, weightShort, type WeightLog, entryDay, BODYWEIGHT_STEP, clampStep } from '@lyftr/shared'
import {
AppText, Button, DateInput, Field, NumberField, NumericKeyboardAccessory, NUMERIC_ACCESSORY_ID,
Sheet, StepperTile,
@@ -33,7 +33,6 @@ export function QuickWeighInSheet({ open, lastValue, lastLog, onClose, onSuccess
const [date, setDate] = useState(todayStr())
const [notes, setNotes] = useState('')
const [showExtras, setShowExtras] = useState(false)
- const [saving, setSaving] = useState(false)
const [error, setError] = useState('')
const [showDuplicateWarning, setShowDuplicateWarning] = useState(false)
const [dupDismissed, setDupDismissed] = useState(false)
@@ -46,13 +45,23 @@ export function QuickWeighInSheet({ open, lastValue, lastLog, onClose, onSuccess
setNotes('')
setShowExtras(false)
setError('')
- setSaving(false)
setShowDuplicateWarning(false)
setDupDismissed(false)
}, [open, lastValue])
+ const save = useAsyncAction(async (w: number) => {
+ const log = await client.weightAPI.log({
+ weight: displayToLbs(w, unit),
+ notes: notes.trim(),
+ logged_at: dayToInstant(date),
+ })
+ Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success).catch(() => {})
+ onSuccess(log)
+ onClose()
+ }, 'Failed to save')
+
const submit = async (forceDismissed = false) => {
- if (saving) return
+ if (save.busy) return
const w = parseFloat(value)
const wErr = weightError(w, unit)
if (wErr) {
@@ -63,22 +72,9 @@ export function QuickWeighInSheet({ open, lastValue, lastLog, onClose, onSuccess
setShowDuplicateWarning(true)
return
}
- setSaving(true)
setError('')
setShowDuplicateWarning(false)
- try {
- const log = await client.weightAPI.log({
- weight: displayToLbs(w, unit),
- notes: notes.trim(),
- logged_at: dayToInstant(date),
- })
- Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success).catch(() => {})
- onSuccess(log)
- onClose()
- } catch (err) {
- setError(apiErrorMessage(err, 'Failed to save'))
- setSaving(false)
- }
+ void save.run(w)
}
return (
@@ -98,10 +94,10 @@ export function QuickWeighInSheet({ open, lastValue, lastLog, onClose, onSuccess
</View>
<View className="gap-4">
- {error ? (
+ {(error || save.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={16} color={brand.errorSoft} />
- <Text className="flex-1 font-sans text-sm text-error-400">{error}</Text>
+ <Text className="flex-1 font-sans text-sm text-error-400">{error || save.error}</Text>
</View>
) : null}
@@ -161,10 +157,10 @@ export function QuickWeighInSheet({ open, lastValue, lastLog, onClose, onSuccess
)}
<Button
- title={saving ? 'Saving…' : 'Save'}
+ title={save.busy ? 'Saving…' : 'Save'}
onPress={() => submit()}
- loading={saving}
- disabled={!(parseFloat(value) > 0) || saving}
+ loading={save.busy}
+ disabled={!(parseFloat(value) > 0) || save.busy}
/>
</View>
</View>
diff --git a/mobile/src/components/nutrition/FoodEntryRow.tsx b/mobile/src/components/nutrition/FoodEntryRow.tsx
index 8f50a98..518a9ab 100644
--- a/mobile/src/components/nutrition/FoodEntryRow.tsx
+++ b/mobile/src/components/nutrition/FoodEntryRow.tsx
@@ -1,3 +1,4 @@
+import { useAsyncAction } from '@lyftr/shared'
import { useState } from 'react'
import { Image, Pressable, View } from 'react-native'
import * as Haptics from 'expo-haptics'
@@ -41,19 +42,15 @@ export function FoodEntryRow({ entry, first, onPress, onEdit, onDeleted }: Props
const { colors } = useTheme()
const [menuOpen, setMenuOpen] = useState(false)
const [confirming, setConfirming] = useState(false)
- const [deleting, setDeleting] = useState(false)
- const handleDelete = async () => {
- setDeleting(true)
- try {
- await client.foodAPI.delete(entry.id)
- Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success).catch(() => {})
- onDeleted(entry.id)
- } catch {
- setDeleting(false)
- setConfirming(false)
- }
- }
+ // The catch here just put the card back - "a failed delete quietly restores the
+ // card" - which is indistinguishable from a tap that never registered. The
+ // confirm stays up now and says why it did not work.
+ const remove = useAsyncAction(async () => {
+ await client.foodAPI.delete(entry.id)
+ Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success).catch(() => {})
+ onDeleted(entry.id)
+ }, 'Failed to delete entry')
const Thumb = ({ size = 44 }: { size?: number }) =>
entry.image_url ? (
@@ -109,7 +106,7 @@ export function FoodEntryRow({ entry, first, onPress, onEdit, onDeleted }: Props
variant="ghost"
size="sm"
onPress={() => setMenuOpen(true)}
- disabled={deleting}
+ disabled={remove.busy}
/>
<ChevronRight size={16} color={colors.txMuted} />
@@ -135,9 +132,10 @@ export function FoodEntryRow({ entry, first, onPress, onEdit, onDeleted }: Props
<ConfirmSheet
{...deleteConfirmProps({ title: 'Delete entry?', subject: `"${entry.name}"` })}
open={confirming}
- busy={deleting}
- onConfirm={handleDelete}
- onCancel={() => setConfirming(false)}
+ busy={remove.busy}
+ error={remove.error}
+ onConfirm={() => { void remove.run() }}
+ onCancel={() => { setConfirming(false); remove.reset() }}
/>
</Pressable>
)
diff --git a/mobile/src/components/programs/ProgramCard.tsx b/mobile/src/components/programs/ProgramCard.tsx
index 63972bd..dad2332 100644
--- a/mobile/src/components/programs/ProgramCard.tsx
+++ b/mobile/src/components/programs/ProgramCard.tsx
@@ -4,7 +4,7 @@ import { router, type Href } from 'expo-router'
import { format } from 'date-fns'
import { BookOpen, ChevronRight, Dumbbell, Layers, Moon, MoreVertical, Play, Sun } from 'lucide-react-native'
import type { Program, ProgramDay } from '@lyftr/shared'
-import {
+import { useAsyncAction,
activeSessionExercisesForDay, allExercises, dayLabel, isDayStartable, programExerciseCount, programSetCount,
sessionNameForDay, todaysDay,
} from '@lyftr/shared'
@@ -32,7 +32,6 @@ const activeHref = '/workouts/active' as unknown as Href
export function ProgramCard({ program, onPress, onDeleted }: Props) {
const { colors, accent } = useTheme()
const { session, startSession } = useWorkoutSession()
- const [deleting, setDeleting] = useState(false)
const [confirming, setConfirming] = useState(false)
const [menuOpen, setMenuOpen] = useState(false)
const [dayPickFor, setDayPickFor] = useState<Program | null>(null)
@@ -66,17 +65,13 @@ export function ProgramCard({ program, onPress, onDeleted }: Props) {
pickProgramDay(program, (_p, day) => beginSession(day), setDayPickFor, () => router.push(`/programs/${program.id}`))
}
- const handleDelete = async () => {
- setDeleting(true)
- try {
- await client.programAPI.delete(program.id)
- onDeleted(program.id)
- } catch {
- // Web parity: a failed delete quietly restores the card.
- setDeleting(false)
- setConfirming(false)
- }
- }
+ // The catch here just put the card back - "a failed delete quietly restores the
+ // card" - which is indistinguishable from a tap that never registered. The
+ // confirm stays up now and says why it did not work.
+ const remove = useAsyncAction(async () => {
+ await client.programAPI.delete(program.id)
+ onDeleted(program.id)
+ }, 'Failed to delete program')
return (
<Pressable accessibilityRole="button" onPress={onPress} className="active:scale-[0.99]">
@@ -130,7 +125,7 @@ export function ProgramCard({ program, onPress, onDeleted }: Props) {
variant="solid"
size="sm"
onPress={handleStart}
- disabled={deleting}
+ disabled={remove.busy}
/>
<IconButton
icon={MoreVertical}
@@ -138,7 +133,7 @@ export function ProgramCard({ program, onPress, onDeleted }: Props) {
variant="ghost"
size="sm"
onPress={() => setMenuOpen(true)}
- disabled={deleting}
+ disabled={remove.busy}
/>
<ChevronRight size={16} color={colors.txMuted} />
</Card>
@@ -167,9 +162,10 @@ export function ProgramCard({ program, onPress, onDeleted }: Props) {
<ConfirmSheet
{...deleteConfirmProps({ title: 'Delete Program?', subject: `"${program.name}"` })}
open={confirming}
- busy={deleting}
- onConfirm={handleDelete}
- onCancel={() => setConfirming(false)}
+ busy={remove.busy}
+ error={remove.error}
+ onConfirm={() => { void remove.run() }}
+ onCancel={() => { setConfirming(false); remove.reset() }}
/>
<DayPickerSheet program={dayPickFor} onSelect={(_p, day) => beginSession(day)} onClose={() => setDayPickFor(null)} />
diff --git a/mobile/src/components/ui/Alert.tsx b/mobile/src/components/ui/Alert.tsx
index 18a5af8..44b04e0 100644
--- a/mobile/src/components/ui/Alert.tsx
+++ b/mobile/src/components/ui/Alert.tsx
@@ -33,20 +33,26 @@ interface Props {
variant: Variant
children: ReactNode
className?: string
+ /** 'compact' for dense surfaces — inside a sheet, where a full-size alert outweighs
+ * the copy it is qualifying and pushes the buttons off a short screen. */
+ size?: 'default' | 'compact'
}
-export function Alert({ variant, children, className = '' }: Props) {
+export function Alert({ variant, children, className = '', size = 'default' }: Props) {
const { brand } = useTheme()
const { icon: Icon, tone } = TONES[variant]
const color = brand[tone]
+ const compact = size === 'compact'
return (
<View
accessibilityRole="alert"
- className={`flex-row items-start gap-3 rounded-lg border p-3.5 ${SURFACES[variant]} ${className}`}
+ className={`flex-row items-start rounded-lg border ${
+ compact ? 'gap-2.5 px-3 py-2.5' : 'gap-3 p-3.5'
+ } ${SURFACES[variant]} ${className}`}
>
- <Icon size={18} color={color} strokeWidth={2.2} style={{ marginTop: 1 }} />
- <AppText variant="body" className="flex-1" style={{ color }}>
+ <Icon size={compact ? 15 : 18} color={color} strokeWidth={2.2} style={{ marginTop: compact ? 1.5 : 1 }} />
+ <AppText variant={compact ? 'caption' : 'body'} className="flex-1" style={{ color }}>
{children}
</AppText>
</View>
diff --git a/mobile/src/components/ui/ConfirmSheet.tsx b/mobile/src/components/ui/ConfirmSheet.tsx
index f22269c..c5d8382 100644
--- a/mobile/src/components/ui/ConfirmSheet.tsx
+++ b/mobile/src/components/ui/ConfirmSheet.tsx
@@ -2,6 +2,7 @@ import { View } from 'react-native'
import type { LucideIcon } from 'lucide-react-native'
import { useTheme } from '../../theme/useTheme'
import { AppText } from './Typography'
+import { Alert } from './Alert'
import { SheetButton } from './SheetButton'
import { Sheet } from './Sheet'
@@ -56,11 +57,7 @@ export function ConfirmSheet({
<AppText variant="heading" className="mb-1.5 text-center">{title}</AppText>
<AppText variant="body" color="muted" className="mb-6 text-center">{message}</AppText>
- {error ? (
- <View className="mb-5 rounded-xl border border-error-500/20 bg-error-500/10 px-3.5 py-3">
- <AppText variant="caption" color="error" className="text-center">{error}</AppText>
- </View>
- ) : null}
+ {error ? <Alert variant="error" size="compact" className="mb-5">{error}</Alert> : null}
<View className="flex-row gap-3">
<View className="flex-1">
diff --git a/mobile/src/components/weight/WeightEntryRow.tsx b/mobile/src/components/weight/WeightEntryRow.tsx
index 76cbeb0..00ed1e2 100644
--- a/mobile/src/components/weight/WeightEntryRow.tsx
+++ b/mobile/src/components/weight/WeightEntryRow.tsx
@@ -3,7 +3,7 @@ import { Pressable, Text, View } from 'react-native'
import { router } from 'expo-router'
import * as Haptics from 'expo-haptics'
import { ChevronRight, MoreVertical, Scale, TrendingDown, TrendingUp } from 'lucide-react-native'
-import { displayWeight, entryDay, weightShort, type WeightLog, formatDay } from '@lyftr/shared'
+import { useAsyncAction, displayWeight, entryDay, weightShort, type WeightLog, formatDay } from '@lyftr/shared'
import { ActionSheet, AppText, Card, ConfirmSheet, IconButton, deleteAction, deleteConfirmProps, editAction } from '../ui'
import { useTheme } from '../../theme/useTheme'
import { client } from '../../lib/lyftr'
@@ -26,24 +26,20 @@ export function WeightEntryRow({ item, next, unit, onDeleted }: Props) {
const wUnit = weightShort(unit)
const [menuOpen, setMenuOpen] = useState(false)
const [confirming, setConfirming] = useState(false)
- const [deleting, setDeleting] = useState(false)
const deltaLbs = next ? item.weight - next.weight : 0
const displayW = displayWeight(item.weight, unit)
const displayDelta = displayWeight(Math.abs(deltaLbs), unit)
const dateLabel = formatDay(entryDay(item), 'MMM d, yyyy')
- const handleDelete = async () => {
- setDeleting(true)
- try {
- await client.weightAPI.delete(item.id)
- Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success).catch(() => {})
- onDeleted(item.id)
- } catch {
- setDeleting(false)
- setConfirming(false)
- }
- }
+ // The catch here just put the card back - "a failed delete quietly restores the
+ // card" - which is indistinguishable from a tap that never registered. The
+ // confirm stays up now and says why it did not work.
+ const remove = useAsyncAction(async () => {
+ await client.weightAPI.delete(item.id)
+ Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success).catch(() => {})
+ onDeleted(item.id)
+ }, 'Failed to delete entry')
return (
<Pressable onPress={() => router.push(`/weight/${item.id}`)} className="mb-2 active:scale-[0.99]">
@@ -77,7 +73,7 @@ export function WeightEntryRow({ item, next, unit, onDeleted }: Props) {
variant="ghost"
size="sm"
onPress={() => setMenuOpen(true)}
- disabled={deleting}
+ disabled={remove.busy}
/>
<ChevronRight size={16} color={colors.txMuted} />
</Card>
@@ -108,9 +104,10 @@ export function WeightEntryRow({ item, next, unit, onDeleted }: Props) {
<ConfirmSheet
{...deleteConfirmProps({ title: 'Delete Entry?', subject: `${dateLabel} · ${Math.round(displayW)} ${wUnit}` })}
open={confirming}
- busy={deleting}
- onConfirm={handleDelete}
- onCancel={() => setConfirming(false)}
+ busy={remove.busy}
+ error={remove.error}
+ onConfirm={() => { void remove.run() }}
+ onCancel={() => { setConfirming(false); remove.reset() }}
/>
</Pressable>
)
diff --git a/mobile/src/components/workouts/GymModeWorkout.tsx b/mobile/src/components/workouts/GymModeWorkout.tsx
index aa19ba3..eb125d7 100644
--- a/mobile/src/components/workouts/GymModeWorkout.tsx
+++ b/mobile/src/components/workouts/GymModeWorkout.tsx
@@ -9,7 +9,7 @@ import {
Play, Plus, Repeat, Timer, Trash2, X,
} from 'lucide-react-native'
import {
- apiErrorMessage, displayToLbs, displayWeight, weightShort, type Exercise,
+ useAsyncAction, displayToLbs, displayWeight, weightShort, type Exercise,
} from '@lyftr/shared'
import { AppText, ConfirmSheet, NumberField, NumericKeyboardAccessory, NUMERIC_ACCESSORY_ID, StepperTile } from '../ui'
import { RestPicker } from './RestPicker'
@@ -85,8 +85,6 @@ export function GymModeWorkout() {
const [imgFailed, setImgFailed] = useState(false)
const [confirmFinish, setConfirmFinish] = useState(false)
const [confirmCancel, setConfirmCancel] = useState(false)
- const [saving, setSaving] = useState(false)
- const [saveError, setSaveError] = useState('')
const [showPicker, setShowPicker] = useState(false)
const setPhase = (p: typeof phase) => setGymState(p, activeIdx, activeSetIdx)
@@ -113,29 +111,24 @@ export function GymModeWorkout() {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [activeIdx, session?.exercises.length])
+ // The sheet stays OPEN when this fails. The session is intact and the server may
+ // be reachable again in a moment, so the retry belongs under the finger that just
+ // tapped Finish - the alternative, dismissing to a banner at the top of a scrolled
+ // list, is what #145 felt like from the user's seat.
+ const finish = useAsyncAction(async () => {
+ const created = await client.workoutAPI.create(buildPayload())
+ setOutcome({ kind: 'saved', workoutId: created.id, progression: created.progression })
+ cancelSession()
+ minimizeGym()
+ router.replace('/workouts')
+ }, 'Failed to save workout')
+
if (!session) return null
const totalSets = session.exercises.reduce((s, ex) => s + ex.sets.length, 0)
const completedSets = session.exercises.reduce((s, ex) => s + ex.sets.filter((st) => st.completed).length, 0)
const allDone = completedSets === totalSets && totalSets > 0
- const handleFinish = async () => {
- setSaving(true)
- setSaveError('')
- try {
- const created = await client.workoutAPI.create(buildPayload())
- setOutcome({ kind: 'saved', workoutId: created.id, progression: created.progression })
- cancelSession()
- minimizeGym()
- router.replace('/workouts')
- } catch (err: any) {
- // This used to swallow the error and dismiss the sheet, so a finish that failed
- // looked exactly like a finish that was never registered - the report in #145.
- // Keep the sheet up, say why, leave the session intact, let them tap again.
- setSaveError(apiErrorMessage(err, 'Failed to save workout'))
- setSaving(false)
- }
- }
const handleMinimize = () => {
minimizeGym()
@@ -169,9 +162,9 @@ export function GymModeWorkout() {
icon={Flag}
title="Finish Workout?"
message={`${completedSets} of ${totalSets} sets completed. Workout will be saved.`}
- confirmLabel="Finish" busyLabel="Saving…" cancelLabel="Keep Going" busy={saving}
- error={saveError}
- onConfirm={handleFinish} onCancel={() => { setConfirmFinish(false); setSaveError('') }}
+ confirmLabel="Finish" busyLabel="Saving…" cancelLabel="Keep Going" busy={finish.busy}
+ error={finish.error}
+ onConfirm={() => { void finish.run() }} onCancel={() => { setConfirmFinish(false); finish.reset() }}
/>
<ConfirmSheet
open={confirmCancel}
diff --git a/mobile/src/components/workouts/WorkoutCard.tsx b/mobile/src/components/workouts/WorkoutCard.tsx
index 04fc0f8..f61f43d 100644
--- a/mobile/src/components/workouts/WorkoutCard.tsx
+++ b/mobile/src/components/workouts/WorkoutCard.tsx
@@ -2,7 +2,7 @@ import { useState } from 'react'
import { Pressable, View } from 'react-native'
import { router } from 'expo-router'
import { ChevronRight, Clock, Dumbbell, MoreVertical, TrendingUp } from 'lucide-react-native'
-import { displayVolume, type Workout, workoutDay, formatDay } from '@lyftr/shared'
+import { useAsyncAction, displayVolume, type Workout, workoutDay, formatDay } from '@lyftr/shared'
import { ActionSheet, AppText, Card, ConfirmSheet, IconButton, deleteAction, deleteConfirmProps, editAction } from '../ui'
import { useTheme } from '../../theme/useTheme'
import { client } from '../../lib/lyftr'
@@ -22,7 +22,6 @@ interface Props {
// the menu is a native ActionSheet and Delete routes through the shared ConfirmSheet.
export function WorkoutCard({ workout, unit, onPress, onDeleted }: Props) {
const { colors } = useTheme()
- const [deleting, setDeleting] = useState(false)
const [confirming, setConfirming] = useState(false)
const [menuOpen, setMenuOpen] = useState(false)
@@ -39,17 +38,13 @@ export function WorkoutCard({ workout, unit, onPress, onDeleted }: Props) {
unit
)
- const handleDelete = async () => {
- setDeleting(true)
- try {
- await client.workoutAPI.delete(workout.id)
- onDeleted(workout.id)
- } catch {
- // Web parity: a failed delete quietly restores the card.
- setDeleting(false)
- setConfirming(false)
- }
- }
+ // The catch here just put the card back - "a failed delete quietly restores the
+ // card" - which is indistinguishable from a tap that never registered. The
+ // confirm stays up now and says why it did not work.
+ const remove = useAsyncAction(async () => {
+ await client.workoutAPI.delete(workout.id)
+ onDeleted(workout.id)
+ }, 'Failed to delete workout')
return (
<Pressable accessibilityRole="button" onPress={onPress} className="active:scale-[0.99]">
@@ -103,7 +98,7 @@ export function WorkoutCard({ workout, unit, onPress, onDeleted }: Props) {
variant="ghost"
size="sm"
onPress={() => setMenuOpen(true)}
- disabled={deleting}
+ disabled={remove.busy}
/>
<ChevronRight size={16} color={colors.txMuted} />
</Card>
@@ -142,9 +137,10 @@ export function WorkoutCard({ workout, unit, onPress, onDeleted }: Props) {
<ConfirmSheet
{...deleteConfirmProps({ title: 'Delete Workout?', subject: `"${workout.name}"` })}
open={confirming}
- busy={deleting}
- onConfirm={handleDelete}
- onCancel={() => setConfirming(false)}
+ busy={remove.busy}
+ error={remove.error}
+ onConfirm={() => { void remove.run() }}
+ onCancel={() => { setConfirming(false); remove.reset() }}
/>
</Pressable>
)