forked from TrustUp-app/TrustUp-Frontend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuse-settings.ts
More file actions
75 lines (64 loc) · 2 KB
/
Copy pathuse-settings.ts
File metadata and controls
75 lines (64 loc) · 2 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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import AsyncStorage from '@react-native-async-storage/async-storage';
import { useCallback, useEffect, useState } from 'react';
export type AppLanguage = 'en' | 'es';
/**
* User-configurable app settings, persisted locally with AsyncStorage.
*/
export interface AppSettings {
/** Loan reminder push notifications on/off. */
loanReminders: boolean;
/** Automatically pay loans on their due date. */
autoPay: boolean;
/** Preferred UI language. */
language: AppLanguage;
/** Dark theme enabled. */
darkMode: boolean;
}
export interface UseSettingsReturn {
settings: AppSettings;
isLoading: boolean;
update: (partial: Partial<AppSettings>) => Promise<void>;
}
const STORAGE_KEY = 'trustup.settings';
const DEFAULT_SETTINGS: AppSettings = {
loanReminders: true,
autoPay: true,
language: 'en',
darkMode: false,
};
/**
* Reads and writes app settings from AsyncStorage. Settings do not require an
* API call; they are persisted locally per the issue spec.
*/
export const useSettings = (): UseSettingsReturn => {
const [settings, setSettings] = useState<AppSettings>(DEFAULT_SETTINGS);
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
let active = true;
(async () => {
try {
const raw = await AsyncStorage.getItem(STORAGE_KEY);
if (active && raw) {
setSettings({ ...DEFAULT_SETTINGS, ...(JSON.parse(raw) as Partial<AppSettings>) });
}
} catch {
// Keep defaults on read/parse failure.
} finally {
if (active) setIsLoading(false);
}
})();
return () => {
active = false;
};
}, []);
const update = useCallback(async (partial: Partial<AppSettings>) => {
setSettings((prev) => {
const next = { ...prev, ...partial };
AsyncStorage.setItem(STORAGE_KEY, JSON.stringify(next)).catch(() => {
// Ignore write failures; state already reflects the change optimistically.
});
return next;
});
}, []);
return { settings, isLoading, update };
};