fuse_expo/app/_layout.tsx

101 lines
2.7 KiB
TypeScript
Raw Normal View History

import { DarkTheme, DefaultTheme, ThemeProvider } from '@react-navigation/native';
import { useFonts } from 'expo-font';
import { Stack } from 'expo-router';
import * as SplashScreen from 'expo-splash-screen';
import 'react-native-reanimated';
import { useColorScheme } from '@/hooks/useColorScheme';
2024-09-10 00:59:55 -05:00
import React, { useState, useEffect } from 'react';
import AsyncStorage from '@react-native-async-storage/async-storage';
import UserSelection from '@/components/UserSelection';
import { TouchableOpacity, Text } from 'react-native';
type User = {
id: number;
name: string;
message: string;
};
// Prevent the splash screen from auto-hiding before asset loading is complete.
SplashScreen.preventAutoHideAsync();
export default function RootLayout() {
const colorScheme = useColorScheme();
2024-09-10 00:59:55 -05:00
const [loaded, error] = useFonts({
SpaceMono: require('../assets/fonts/SpaceMono-Regular.ttf'),
});
2024-09-10 00:59:55 -05:00
const [user, setUser] = useState<User | null>(null);
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
async function prepare() {
try {
// Load the user
const storedUser = await AsyncStorage.getItem('@user');
if (storedUser) {
setUser(JSON.parse(storedUser));
}
} catch (e) {
console.error('Failed to load user', e);
} finally {
setIsLoading(false);
}
}
prepare();
}, []);
useEffect(() => {
if (loaded) {
SplashScreen.hideAsync();
}
}, [loaded]);
2024-09-10 00:59:55 -05:00
const handleUserSelected = async (selectedUser: User) => {
setUser(selectedUser);
try {
await AsyncStorage.setItem('@user', JSON.stringify(selectedUser));
} catch (e) {
console.error('Failed to save user', e);
}
};
const handleSwitchUser = async () => {
try {
await AsyncStorage.removeItem('@user');
setUser(null);
} catch (e) {
console.error('Failed to remove user', e);
}
};
if (!loaded || isLoading) {
return null; // or a loading indicator
}
if (!user) {
return <UserSelection onUserSelected={handleUserSelected} />;
}
return (
<ThemeProvider value={colorScheme === 'dark' ? DarkTheme : DefaultTheme}>
<Stack>
2024-09-10 00:59:55 -05:00
<Stack.Screen
name="(tabs)"
options={{
headerShown: true,
title: user.name,
headerRight: () => (
<TouchableOpacity onPress={handleSwitchUser} style={{ marginRight: 15 }}>
<Text style={{ color: colorScheme === 'dark' ? 'white' : 'black' }}>
Switch User
</Text>
</TouchableOpacity>
),
}}
/>
<Stack.Screen name="+not-found" />
</Stack>
</ThemeProvider>
);
}