Saving API key on startup and fixed various deprecated messages

This commit is contained in:
Florian 2025-10-15 10:00:23 +02:00
parent f10d8d0777
commit 8895bc9c9d
6 changed files with 59 additions and 69 deletions

View File

@ -1,50 +1,57 @@
import AsyncStorage from "@react-native-async-storage/async-storage"; import AsyncStorage from "@react-native-async-storage/async-storage";
import * as Notifications from "expo-notifications"; import * as Notifications from "expo-notifications";
import React, { useEffect, useState } from "react"; import React, { useEffect, useState } from "react";
import { Linking, SafeAreaView, ScrollView, Text, TouchableOpacity, View } from "react-native"; import { Linking, ScrollView, Text, TextInput, TouchableOpacity, View } from "react-native";
import { SafeAreaView } from "react-native-safe-area-context";
import { Category, categories, categoryKeys, categoryTitles } from "types/Category"; import { Category, categories, categoryKeys, categoryTitles } from "types/Category";
import { Item } from "types/Item"; import { Item } from "types/Item";
import { usePushNotifications } from "../hooks/usePushNotifications"; import { usePushNotifications } from "../hooks/usePushNotifications";
import { styles } from "./HomeScreen.styles"; import { styles } from "../styles/HomeScreen.styles";
const API_URL = "https://notifier.gansejunge.com"; const API_URL = "https://notifier.gansejunge.com";
const STORAGE_KEY = "notifications"; const STORAGE_KEY = "notifications";
const API_KEY_STORAGE = "api_key";
export default function HomeScreen() { export default function HomeScreen() {
const [data, setData] = useState<Item[]>([]); const [data, setData] = useState<Item[]>([]);
const [selected, setSelected] = useState<Category>("home"); const [selected, setSelected] = useState<Category>("home");
const [menuOpen, setMenuOpen] = useState(false); const [menuOpen, setMenuOpen] = useState(false);
const [apiKey, setApiKey] = useState<string | null>(null);
const [tempKey, setTempKey] = useState("");
// Register push notifications const pushToken = usePushNotifications({
usePushNotifications({ apiKey,
userId: 1,
apiKey: "super-secret-api-key",
backendUrl: API_URL, backendUrl: API_URL,
appVersion: "1.0.0", appVersion: "1.0.0",
locale: "en-uk", locale: "en-uk",
}); });
// Load saved notifications on startup // Load API key on startup
useEffect(() => {
(async () => {
const storedKey = await AsyncStorage.getItem(API_KEY_STORAGE);
if (storedKey) setApiKey(storedKey);
})();
}, []);
// Load saved notifications
useEffect(() => { useEffect(() => {
(async () => { (async () => {
try { try {
const stored = await AsyncStorage.getItem(STORAGE_KEY); const stored = await AsyncStorage.getItem(STORAGE_KEY);
if (stored) { if (stored) setData(JSON.parse(stored));
setData(JSON.parse(stored));
}
} catch (err) { } catch (err) {
console.error("Failed to load stored notifications:", err); console.error("Failed to load stored notifications:", err);
} }
})(); })();
}, []); }, []);
// Listen for incoming notifications // Listen for incoming notifications
useEffect(() => { useEffect(() => {
const subscription = Notifications.addNotificationReceivedListener(notification => { const subscription = Notifications.addNotificationReceivedListener(notification => {
const rawCategory = notification.request.content.data?.category as Category | undefined; const rawCategory = notification.request.content.data?.category as Category | undefined;
const category: Category = rawCategory && categoryKeys.includes(rawCategory) const category: Category = rawCategory && categoryKeys.includes(rawCategory) ? rawCategory : "home";
? rawCategory
: "home";
const item: Item = { const item: Item = {
timestamp: Date.now(), timestamp: Date.now(),
@ -60,15 +67,36 @@ export default function HomeScreen() {
return updated; return updated;
}); });
}); });
return () => subscription.remove(); return () => subscription.remove();
}, []); }, []);
// Filtered view: home shows everything
const filteredData = selected === "home" ? data : data.filter(item => item.category === selected); const filteredData = selected === "home" ? data : data.filter(item => item.category === selected);
const menuItems = categories; const menuItems = categories;
if (!apiKey) {
return (
<SafeAreaView style={styles.container}>
<View style={{ padding: 20 }}>
<Text style={{ marginBottom: 10 }}>Enter API Key:</Text>
<TextInput
value={tempKey}
onChangeText={setTempKey}
style={{ borderWidth: 1, padding: 8, marginBottom: 10 }}
/>
<TouchableOpacity
onPress={async () => {
await AsyncStorage.setItem(API_KEY_STORAGE, tempKey);
setApiKey(tempKey);
}}
style={{ backgroundColor: "blue", padding: 10 }}
>
<Text style={{ color: "white" }}>Save</Text>
</TouchableOpacity>
</View>
</SafeAreaView>
);
}
return ( return (
<SafeAreaView style={styles.container}> <SafeAreaView style={styles.container}>
{/* Side Menu */} {/* Side Menu */}
@ -92,7 +120,6 @@ export default function HomeScreen() {
<TouchableOpacity style={styles.menuButton} onPress={() => setMenuOpen(!menuOpen)}> <TouchableOpacity style={styles.menuButton} onPress={() => setMenuOpen(!menuOpen)}>
<Text style={styles.menuButtonText}></Text> <Text style={styles.menuButtonText}></Text>
</TouchableOpacity> </TouchableOpacity>
<Text style={styles.title}>{categoryTitles[selected]}</Text> <Text style={styles.title}>{categoryTitles[selected]}</Text>
<ScrollView style={styles.dataContainer}> <ScrollView style={styles.dataContainer}>
@ -114,3 +141,4 @@ export default function HomeScreen() {
</SafeAreaView> </SafeAreaView>
); );
} }

View File

@ -68,10 +68,7 @@ const styles = StyleSheet.create({
borderRadius: 8, borderRadius: 8,
padding: 16, padding: 16,
marginBottom: 12, marginBottom: 12,
shadowColor: '#000', boxShadow: '0 2px 4px rgba(0,0,0,0.05)',
shadowOpacity: 0.05,
shadowRadius: 4,
elevation: 2,
}, },
dataTitle: { dataTitle: {
fontSize: 18, fontSize: 18,

View File

@ -1,6 +1,11 @@
import React from 'react'; import React from 'react';
import { SafeAreaProvider } from "react-native-safe-area-context";
import HomeScreen from './HomeScreen'; import HomeScreen from './HomeScreen';
export default function App() { export default function App() {
return <HomeScreen />; return (
<SafeAreaProvider>
<HomeScreen />
</SafeAreaProvider>
);
} }

View File

@ -1,35 +0,0 @@
import * as Device from 'expo-device';
import * as Notifications from 'expo-notifications';
import { Platform } from 'react-native';
export async function registerForPushNotificationsAsync() {
if (!Device.isDevice) {
alert('Must use physical device for Push Notifications');
return null;
}
const { status: existingStatus } = await Notifications.getPermissionsAsync();
let finalStatus = existingStatus;
if (existingStatus !== 'granted') {
const { status } = await Notifications.requestPermissionsAsync();
finalStatus = status;
}
if (finalStatus !== 'granted') {
alert('Failed to get push token for push notification!');
return null;
}
const token = (await Notifications.getExpoPushTokenAsync()).data;
console.log('Expo Push Token:', token);
if (Platform.OS === 'android') {
await Notifications.setNotificationChannelAsync('default', {
name: 'default',
importance: Notifications.AndroidImportance.MAX,
});
}
return token;
}

View File

@ -4,8 +4,7 @@ import { useEffect, useState } from "react";
import { Platform } from "react-native"; import { Platform } from "react-native";
type RegisterTokenParams = { type RegisterTokenParams = {
userId: number; apiKey?: string | null;
apiKey: string;
backendUrl: string; backendUrl: string;
appVersion?: string; appVersion?: string;
locale?: string; locale?: string;
@ -13,16 +12,16 @@ type RegisterTokenParams = {
}; };
export function usePushNotifications({ export function usePushNotifications({
userId,
apiKey, apiKey,
backendUrl, backendUrl,
appVersion = "1.0.0", appVersion = "1.0.0",
locale, locale,
topics topics
}: RegisterTokenParams) { }: RegisterTokenParams & { apiKey?: string | null }) {
const [expoPushToken, setExpoPushToken] = useState<string | null>(null); const [expoPushToken, setExpoPushToken] = useState<string | null>(null);
useEffect(() => { useEffect(() => {
if (!apiKey) return;
(async () => { (async () => {
const token = await registerForPushNotificationsAsync(); const token = await registerForPushNotificationsAsync();
if (token) { if (token) {
@ -30,7 +29,7 @@ export function usePushNotifications({
await registerTokenWithBackend(token); await registerTokenWithBackend(token);
} }
})(); })();
}, []); }, [apiKey]);
const registerTokenWithBackend = async (token: string) => { const registerTokenWithBackend = async (token: string) => {
try { try {
@ -38,10 +37,9 @@ export function usePushNotifications({
method: "POST", method: "POST",
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
"X-API-Key": apiKey "X-API-Key": apiKey ?? "",
}, },
body: JSON.stringify({ body: JSON.stringify({
user_id: userId,
token, token,
platform: Platform.OS, platform: Platform.OS,
app_ver: appVersion, app_ver: appVersion,

View File

@ -60,14 +60,11 @@ export const styles = StyleSheet.create({
width: "90%", width: "90%",
}, },
dataItem: { dataItem: {
backgroundColor: "#fff", backgroundColor: '#fff',
borderRadius: 8, borderRadius: 8,
padding: 16, padding: 16,
marginBottom: 12, marginBottom: 12,
shadowColor: "#000", boxShadow: '0 2px 4px rgba(0,0,0,0.05)',
shadowOpacity: 0.05,
shadowRadius: 4,
elevation: 2,
}, },
dataTitle: { dataTitle: {
fontSize: 18, fontSize: 18,