Massive/EditSet.tsx

80 lines
2.3 KiB
TypeScript
Raw Normal View History

2022-07-11 00:28:30 +00:00
import {
RouteProp,
useFocusEffect,
useNavigation,
useRoute,
} from '@react-navigation/native';
2022-07-20 03:48:48 +00:00
import React, {useCallback, useContext} from 'react';
import {NativeModules, View} from 'react-native';
import {IconButton} from 'react-native-paper';
import {DatabaseContext} from './App';
2022-07-11 00:28:30 +00:00
import {HomePageParams} from './HomePage';
import Set from './set';
2022-07-20 03:48:48 +00:00
import SetForm from './SetForm';
import Settings from './settings';
2022-07-03 01:50:01 +00:00
export default function EditSet() {
2022-07-11 00:28:30 +00:00
const {params} = useRoute<RouteProp<HomePageParams, 'EditSet'>>();
const db = useContext(DatabaseContext);
const navigation = useNavigation();
2022-07-11 00:28:30 +00:00
useFocusEffect(
useCallback(() => {
navigation.getParent()?.setOptions({
headerLeft: () => (
<IconButton icon="arrow-back" onPress={() => navigation.goBack()} />
),
title: 'Set',
});
2022-07-11 00:32:13 +00:00
}, [navigation]),
2022-07-11 00:28:30 +00:00
);
2022-08-20 04:37:59 +00:00
const startTimer = useCallback(async () => {
const [result] = await db.executeSql(`SELECT * FROM settings LIMIT 1`);
const settings: Settings = result.rows.item(0);
if (!settings.alarm) return;
const milliseconds = settings.minutes * 60 * 1000 + settings.seconds * 1000;
NativeModules.AlarmModule.timer(milliseconds, !!settings.vibrate);
}, [db]);
2022-07-20 03:48:48 +00:00
const update = useCallback(
async (set: Set) => {
console.log(`${EditSet.name}.update`, set);
await db.executeSql(
`UPDATE sets SET name = ?, reps = ?, weight = ?, created = ?, unit = ? WHERE id = ?`,
[set.name, set.reps, set.weight, set.created, set.unit, set.id],
);
navigation.goBack();
},
[db, navigation],
);
2022-07-20 03:48:48 +00:00
const add = useCallback(
async (set: Set) => {
const {name, reps, weight, unit} = set;
2022-07-20 03:48:48 +00:00
const insert = `
INSERT INTO sets(name, reps, weight, created, unit)
VALUES (?,?,?,strftime('%Y-%m-%dT%H:%M:%S', 'now', 'localtime'),?)
2022-07-20 03:48:48 +00:00
`;
2022-08-20 04:37:59 +00:00
startTimer();
await db.executeSql(insert, [name, reps, weight, unit]);
2022-07-20 03:48:48 +00:00
navigation.goBack();
},
2022-08-20 04:37:59 +00:00
[db, navigation, startTimer],
2022-07-20 03:48:48 +00:00
);
const save = useCallback(
async (set: Set) => {
if (params.set.id) return update(set);
return add(set);
},
[update, add, params.set.id],
);
2022-07-03 01:50:01 +00:00
return (
2022-07-11 00:28:30 +00:00
<View style={{padding: 10}}>
2022-08-24 00:46:47 +00:00
<SetForm save={save} set={params.set} next={params.next} />
2022-07-11 00:28:30 +00:00
</View>
2022-07-03 01:50:01 +00:00
);
}