Massive/BestPage.tsx

87 lines
2.3 KiB
TypeScript
Raw Normal View History

2022-07-09 01:27:19 +00:00
import React, {useCallback, useContext, useEffect, useState} from 'react';
2022-07-04 04:03:48 +00:00
import {FlatList, StyleSheet, View} from 'react-native';
import {List, Searchbar} from 'react-native-paper';
import {DatabaseContext} from './App';
2022-07-08 12:11:10 +00:00
import Best from './best';
import ViewBest from './ViewBest';
2022-07-03 01:50:01 +00:00
export default function BestPage() {
2022-07-08 12:11:10 +00:00
const [bests, setBests] = useState<Best[]>([]);
2022-07-04 04:03:48 +00:00
const [search, setSearch] = useState('');
const [refreshing, setRefresing] = useState(false);
2022-07-08 12:11:10 +00:00
const [best, setBest] = useState<Best>();
const db = useContext(DatabaseContext);
2022-07-04 04:03:48 +00:00
2022-07-09 01:27:19 +00:00
const refresh = useCallback(async () => {
const bestWeight = `
SELECT name, reps, unit, MAX(weight) AS weight
FROM sets
WHERE name LIKE ?
GROUP BY name;
`;
const bestReps = `
SELECT name, MAX(reps) as reps, unit, weight
FROM sets
WHERE name = ?
AND weight = ?
GROUP BY name;
`;
const [weight] = await db.executeSql(bestWeight, [`%${search}%`]);
2022-07-08 12:11:10 +00:00
if (!weight) return setBests([]);
let newBest: Best[] = [];
for (let i = 0; i < weight.rows.length; i++) {
const [reps] = await db.executeSql(bestReps, [
weight.rows.item(i).name,
weight.rows.item(i).weight,
]);
2022-07-08 12:11:10 +00:00
newBest = newBest.concat(reps.rows.raw());
}
2022-07-08 12:11:10 +00:00
setBests(newBest);
2022-07-09 01:48:45 +00:00
}, [search, db]);
2022-07-04 04:03:48 +00:00
useEffect(() => {
refresh();
2022-07-09 01:48:45 +00:00
}, [search, refresh]);
2022-07-04 04:03:48 +00:00
2022-07-08 12:11:10 +00:00
const renderItem = ({item}: {item: Best}) => (
2022-07-04 04:03:48 +00:00
<List.Item
key={item.name}
title={item.name}
description={`${item.reps} x ${item.weight}${item.unit}`}
2022-07-08 12:11:10 +00:00
onPress={() => setBest(item)}
2022-07-04 04:03:48 +00:00
/>
);
2022-07-03 01:50:01 +00:00
return (
2022-07-04 04:03:48 +00:00
<View style={styles.container}>
<Searchbar placeholder="Search" value={search} onChangeText={setSearch} />
<FlatList
ListEmptyComponent={
<List.Item
title="No exercises yet"
description="Once sets have been added, Exercises list your personal bests."
/>
}
refreshing={refreshing}
onRefresh={async () => {
setRefresing(true);
await refresh();
setRefresing(false);
}}
renderItem={renderItem}
2022-07-08 12:11:10 +00:00
data={bests}
/>
2022-07-08 12:11:10 +00:00
<ViewBest setBest={setBest} best={best} />
2022-07-03 01:50:01 +00:00
</View>
);
}
2022-07-04 04:03:48 +00:00
const styles = StyleSheet.create({
container: {
padding: 10,
flexGrow: 1,
2022-07-08 01:51:00 +00:00
paddingBottom: '10%',
2022-07-04 04:03:48 +00:00
},
});