import AsyncStorage from "@react-native-async-storage/async-storage"; import * as React from "react"; interface User { email: string; } interface AuthContextValue { user: User | null; isHydrated: boolean; login: (email: string, password: string) => Promise; logout: () => Promise; } const authContext = React.createContext(undefined); const STORAGE_KEY = "user"; export function AuthProvider({ children }: { children: React.ReactNode }) { const [user, setUser] = React.useState(null); const [isHydrated, setIsHydrated] = React.useState(false); React.useEffect(() => { const restoreUser = async () => { try { const storedUser = await AsyncStorage.getItem(STORAGE_KEY); if (storedUser) { setUser(JSON.parse(storedUser) as User); } } catch (error) { console.log("Error restoring user", error); } finally { setIsHydrated(true); } }; restoreUser(); }, []); const login = async (email: string, password: string) => { const fakeUser = { email }; await AsyncStorage.setItem(STORAGE_KEY, JSON.stringify(fakeUser)); setUser(fakeUser); } const logout = async () => { await AsyncStorage.removeItem(STORAGE_KEY); setUser(null); } return ( {children} ); } export function useAuth() { const context = React.useContext(authContext); if(!context) { throw new Error("useAuth must be inside AuthProvider"); } return context; }