Massive/EditSet.tsx

83 lines
2.2 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';
2022-08-28 05:25:31 +00:00
import {NativeModules, View} from 'react-native';
2022-07-20 03:48:48 +00:00
import {IconButton} from 'react-native-paper';
import {SnackbarContext} from './App';
import {addSet, getSettings, setSet} from './db';
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';
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 navigation = useNavigation();
const {toast} = useContext(SnackbarContext);
2022-07-11 00:28:30 +00:00
useFocusEffect(
useCallback(() => {
navigation.getParent()?.setOptions({
headerLeft: () => (
<IconButton icon="arrow-back" onPress={() => navigation.goBack()} />
),
headerRight: null,
title: params.set.id ? 'Edit set' : 'Create set',
2022-07-11 00:28:30 +00:00
});
}, [navigation, params.set.id]),
2022-07-11 00:28:30 +00:00
);
2022-08-20 04:37:59 +00:00
const startTimer = useCallback(async () => {
const settings = await getSettings();
if (!settings.alarm) return;
const milliseconds = settings.minutes * 60 * 1000 + settings.seconds * 1000;
NativeModules.AlarmModule.timer(
milliseconds,
!!settings.vibrate,
settings.sound,
);
}, []);
2022-07-20 03:48:48 +00:00
const update = useCallback(
async (set: Set) => {
console.log(`${EditSet.name}.update`, set);
await setSet(set);
2022-07-20 03:48:48 +00:00
navigation.goBack();
},
[navigation],
2022-07-20 03:48:48 +00:00
);
2022-07-20 03:48:48 +00:00
const add = useCallback(
async (set: Set) => {
2022-08-20 04:37:59 +00:00
startTimer();
await addSet(set);
const settings = await getSettings();
if (settings.notify === 0) return navigation.goBack();
2022-08-24 01:04:45 +00:00
if (
set.weight > params.set.weight ||
(set.reps > params.set.reps && set.weight === params.set.weight)
2022-08-24 01:04:45 +00:00
)
2022-08-27 06:09:45 +00:00
toast("Great work King, that's a new record!", 3000);
2022-07-20 03:48:48 +00:00
navigation.goBack();
},
[navigation, startTimer, params.set, toast],
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}}>
<SetForm save={save} set={params.set} workouts={params.workouts} />
2022-07-11 00:28:30 +00:00
</View>
2022-07-03 01:50:01 +00:00
);
}