weegschaal-app/src/screens/NewMeasurementScreen.tsx

85 lines
2.4 KiB
TypeScript

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, getMeasurementByDate, upsertMeasurement } from '../database/db'
type Props = {
navigation: any
}
export default function NewMeasurementScreen({ navigation }: Props) {
const [latest, setLatest] = useState<Partial<Measurement> | undefined>(undefined)
useFocusEffect(
useCallback(() => {
let cancelled = false
const load = async () => {
await initDatabase()
const m = await getLatestMeasurement()
if (!cancelled) {
setLatest(m || {})
}
}
load()
return () => { cancelled = true }
}, [])
)
const handleSubmit = async (m: Measurement) => {
await initDatabase()
const existing = await getMeasurementByDate(m.measuredAt)
if (existing) {
Alert.alert(
'Dubbele datum',
`Er bestaat al een meting van ${new Date(m.measuredAt).toLocaleDateString('nl-NL')}. Overschrijven?`,
[
{ text: 'Annuleren', style: 'cancel' },
{
text: 'Overschrijven',
style: 'destructive',
onPress: () => doSave(m, existing.id),
},
]
)
return
}
doSave(m)
}
const doSave = async (m: Measurement, existingId?: string) => {
if (existingId) {
m.id = existingId
await upsertMeasurement(m)
} else {
await insertMeasurement(m)
}
try {
const { syncAll } = await import('../sync/syncService')
await syncAll()
Alert.alert('Opgeslagen & gesynct', 'Meting is opgeslagen en gesynchroniseerd', [
{ text: 'OK', onPress: () => navigation.goBack() },
])
} catch {
Alert.alert('Opgeslagen', 'Meting is opgeslagen (sync mislukt)', [
{ text: 'OK', onPress: () => navigation.goBack() },
])
}
}
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}
/>
)
}