fix: pre-fill form with latest measurement values on focus

This commit is contained in:
Eddy de Vink 2026-06-27 23:31:00 +02:00
commit 049473c696
2 changed files with 32 additions and 19 deletions

View file

@ -45,6 +45,8 @@ export default function MeasurementForm({ onSubmit, initialValues }: Props) {
return init
})
const weight = parseFloat(values.weight) || 0
const bodyFatPct = parseFloat(values.bodyFatPercentage) || 0
const musclePct = parseFloat(values.musclePercentage) || 0

View file

@ -1,5 +1,6 @@
import React, { useEffect, useState } from 'react'
import { Alert } from 'react-native'
import React, { useCallback, useState } from 'react'
import { View, Text, Alert } from 'react-native'
import { useFocusEffect } from '@react-navigation/native'
import MeasurementForm from '../components/MeasurementForm'
import { Measurement } from '../types'
import { initDatabase, insertMeasurement, getLatestMeasurement } from '../database/db'
@ -11,23 +12,20 @@ type Props = {
export default function NewMeasurementScreen({ navigation }: Props) {
const [latest, setLatest] = useState<Partial<Measurement> | undefined>(undefined)
useEffect(() => {
const load = async () => {
await initDatabase()
const m = await getLatestMeasurement()
if (m) {
setLatest({
weight: m.weight,
bmi: m.bmi,
bodyFatPercentage: m.bodyFatPercentage,
musclePercentage: m.musclePercentage,
visceralFat: m.visceralFat,
bmr: m.bmr,
})
useFocusEffect(
useCallback(() => {
let cancelled = false
const load = async () => {
await initDatabase()
const m = await getLatestMeasurement()
if (!cancelled) {
setLatest(m || {})
}
}
}
load()
}, [])
load()
return () => { cancelled = true }
}, [])
)
const handleSubmit = async (m: Measurement) => {
await initDatabase()
@ -37,5 +35,18 @@ export default function NewMeasurementScreen({ navigation }: Props) {
])
}
return <MeasurementForm onSubmit={handleSubmit} initialValues={latest} />
if (latest === undefined) {
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#f5f5f5' }}>
<Text style={{ color: '#999' }}>Laden...</Text>
</View>
)
}
return (
<MeasurementForm
onSubmit={handleSubmit}
initialValues={latest as Partial<Measurement> | undefined}
/>
)
}