A React Native app for the ultimate thinking partner.
at bf2a37bf805fa5ccc8b5badeeb098f842186e615 81 lines 2.1 kB view raw
1import { create } from 'zustand'; 2import lettaApi from '../api/lettaApi'; 3import Storage, { STORAGE_KEYS } from '../utils/storage'; 4 5interface AuthState { 6 // State 7 apiToken: string; 8 isConnected: boolean; 9 isConnecting: boolean; 10 isLoadingToken: boolean; 11 connectionError: string | null; 12 13 // Actions 14 setToken: (token: string) => void; 15 loadStoredToken: () => Promise<void>; 16 connectWithToken: (token: string) => Promise<void>; 17 logout: () => Promise<void>; 18 clearError: () => void; 19} 20 21export const useAuthStore = create<AuthState>((set, get) => ({ 22 // Initial state 23 apiToken: '', 24 isConnected: false, 25 isConnecting: false, 26 isLoadingToken: true, 27 connectionError: null, 28 29 // Actions 30 setToken: (token: string) => set({ apiToken: token }), 31 32 loadStoredToken: async () => { 33 try { 34 const stored = await Storage.getItem(STORAGE_KEYS.API_TOKEN); 35 if (stored) { 36 set({ apiToken: stored }); 37 await get().connectWithToken(stored); 38 } 39 } catch (error) { 40 console.error('Failed to load stored token:', error); 41 } finally { 42 set({ isLoadingToken: false }); 43 } 44 }, 45 46 connectWithToken: async (token: string) => { 47 set({ isConnecting: true, connectionError: null }); 48 try { 49 lettaApi.setAuthToken(token); 50 const isValid = await lettaApi.testConnection(); 51 52 if (isValid) { 53 set({ isConnected: true }); 54 await Storage.setItem(STORAGE_KEYS.API_TOKEN, token); 55 } else { 56 throw new Error('Invalid API token'); 57 } 58 } catch (error: any) { 59 console.error('Connection failed:', error); 60 set({ 61 connectionError: error.message || 'Failed to connect', 62 isConnected: false 63 }); 64 lettaApi.removeAuthToken(); 65 } finally { 66 set({ isConnecting: false }); 67 } 68 }, 69 70 logout: async () => { 71 await Storage.removeItem(STORAGE_KEYS.API_TOKEN); 72 lettaApi.removeAuthToken(); 73 set({ 74 apiToken: '', 75 isConnected: false, 76 connectionError: null, 77 }); 78 }, 79 80 clearError: () => set({ connectionError: null }), 81}));