-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseIntakes.ts
More file actions
31 lines (29 loc) · 1.27 KB
/
useIntakes.ts
File metadata and controls
31 lines (29 loc) · 1.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import { useState, useCallback } from 'react';
import * as SQLite from 'expo-sqlite';
import { useFocusEffect } from 'expo-router';
import type { IntakeEntry } from '@/types';
import { getIntakesTableName } from '@/utils/sanitizeForSQL';
export function useIntakes(substance_name: string) {
const [ intakes, setIntakes ] = useState([] as IntakeEntry[]);
useFocusEffect(
useCallback(() => {
const fetchIntakes = async () => {
const meTrackerDB = await SQLite.openDatabaseAsync("MeTracker.db", { useNewConnection: true });
const tableName = getIntakesTableName(substance_name);
await meTrackerDB.runAsync(`
CREATE TABLE IF NOT EXISTS ${tableName} (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
time DATETIME DEFAULT CURRENT_TIMESTAMP,
amount REAL NOT NULL
);
`);
const result = await meTrackerDB.getAllAsync(`SELECT * FROM ${tableName}`);
setIntakes(result as IntakeEntry[]);
await meTrackerDB.closeAsync();
}
fetchIntakes();
}, [substance_name])
);
return intakes;
}