### Install expo-native-storage Source: https://github.com/thereallo1026/expo-native-storage/blob/master/README.md Instructions for installing the expo-native-storage library using bun or npm. After installation, a native build is required as the module includes native code and is not compatible with Expo Go. ```bash # bun bunx expo install expo-native-storage # npm npx expo install expo-native-storage ``` -------------------------------- ### Example: Theme Storage Source: https://github.com/thereallo1026/expo-native-storage/blob/master/README.md A practical example of using expo-native-storage to persist user theme preferences. It shows how to save a theme setting and load it when the application starts, providing a default if no theme is found. ```typescript // Save theme preference await Storage.setItem('theme', 'dark'); // Load on app start const theme = await Storage.getItem('theme') || 'light'; ``` -------------------------------- ### Rebuild app for native module linking Source: https://github.com/thereallo1026/expo-native-storage/blob/master/README.md Commands to rebuild the Expo application to link the native module after installation. This step is crucial for native modules and requires a development or production build, not Expo Go. ```bash # For development builds npx expo prebuild --clean npx expo run:ios # or npx expo run:android ``` -------------------------------- ### Migration from AsyncStorage Source: https://context7.com/thereallo1026/expo-native-storage/llms.txt Demonstrates how to migrate from `@react-native-async-storage/async-storage` to `expo-native-storage`, highlighting the similar API and additional object handling methods. ```APIDOC ## Migration from AsyncStorage ### Description Drop-in replacement example showing how to migrate from `@react-native-async-storage/async-storage` to `expo-native-storage`. ### Method `setItem`, `getItem`, `removeItem`, `clear` (async) ### Endpoint N/A (Local storage operations) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript // Before: Using AsyncStorage import AsyncStorage from '@react-native-async-storage/async-storage'; await AsyncStorage.setItem('user', JSON.stringify({ name: 'John' })); const userData = await AsyncStorage.getItem('user'); // After: Using expo-native-storage import Storage from 'expo-native-storage'; // String operations work identically await Storage.setItem('user', JSON.stringify({ name: 'John' })); const userData = await Storage.getItem('user'); // Or use the built-in object methods (no manual JSON handling) await Storage.setObject('user', { name: 'John' }); const userObj = await Storage.getObject<{ name: string }>('user'); await Storage.removeItem('user'); await Storage.clear(); ``` ### Response #### Success Response (200) See individual method documentation for response details. ``` -------------------------------- ### Migrate from AsyncStorage to expo-native-storage Source: https://github.com/thereallo1026/expo-native-storage/blob/master/README.md Demonstrates the simple, drop-in replacement process for migrating from AsyncStorage to expo-native-storage. This involves changing the import statement and using the new Storage class with identical method calls. ```typescript import AsyncStorage from '@react-native-async-storage/async-storage'; await AsyncStorage.setItem('key', 'value'); // After (expo-native-storage) import Storage from 'expo-native-storage'; await Storage.setItem('key', 'value'); ``` -------------------------------- ### Retrieve String Data with Async and Sync APIs Source: https://context7.com/thereallo1026/expo-native-storage/llms.txt Shows how to retrieve string values from storage using asynchronous (getItem) and synchronous (getItemSync) methods. Both methods return the stored string or null if the key is not found. The sync version is useful for immediate access during startup. ```typescript import Storage from 'expo-native-storage'; // Async: Load user session data const authToken = await Storage.getItem('authToken'); if (authToken) { // User is authenticated, proceed with API calls console.log('Token found:', authToken); } else { // Redirect to login console.log('No token, user needs to login'); } // Sync: Load theme preference immediately on app start const theme = Storage.getItemSync('theme') || 'light'; const locale = Storage.getItemSync('locale') || 'en-US'; console.log(`App initialized with theme: ${theme}, locale: ${locale}`); // Output: App initialized with theme: dark, locale: en-US ``` -------------------------------- ### Retrieve Multiple Items Source: https://context7.com/thereallo1026/expo-native-storage/llms.txt Fetches multiple storage items simultaneously by providing an array of keys. Returns an object where keys map to their corresponding values, or null if a key is not found. Efficient for loading multiple settings or configuration values at once. ```typescript import Storage from 'expo-native-storage'; // Load multiple settings at once async function loadUserSettings() { const settings = await Storage.multiGet([ 'theme', 'locale', 'fontSize', 'authToken', 'lastSync' ]); console.log('Theme:', settings.theme); // 'dark' console.log('Locale:', settings.locale); // 'en-US' console.log('Font Size:', settings.fontSize); // null (not set) console.log('Auth Token:', settings.authToken); // 'eyJ...' console.log('Last Sync:', settings.lastSync); // null (not set) return settings; } // Output: // Theme: dark // Locale: en-US // Font Size: null // Auth Token: eyJ... // Last Sync: null // Use in app initialization const config = await Storage.multiGet(['apiUrl', 'timeout', 'retryCount']); const apiUrl = config.apiUrl || 'https://api.default.com'; const timeout = parseInt(config.timeout || '5000'); ``` -------------------------------- ### Authentication Flow with Storage Persistence in TypeScript Source: https://context7.com/thereallo1026/expo-native-storage/llms.txt This TypeScript code demonstrates a full authentication flow using expo-native-storage. It includes initializing app state from storage, logging in users by persisting tokens and user data, logging out users by clearing session data, and updating user preferences like theme. It utilizes both synchronous and asynchronous methods for storage operations. ```typescript import Storage from 'expo-native-storage'; interface User { id: string; email: string; name: string; role: 'admin' | 'user'; } interface AppState { isAuthenticated: boolean; user: User | null; theme: 'light' | 'dark'; } // Initialize app state from storage on startup (sync for immediate availability) function initializeApp(): AppState { const theme = (Storage.getItemSync('theme') as 'light' | 'dark') || 'light'; const user = Storage.getObjectSync('currentUser'); const token = Storage.getItemSync('authToken'); return { isAuthenticated: !!(token && user), user: user, theme: theme }; } // Login and persist session async function login(email: string, password: string): Promise { // Simulate API call const response = { token: 'jwt-token-here', user: { id: '123', email, name: 'John Doe', role: 'user' as const } }; // Store session data await Storage.multiSet({ authToken: response.token, loginTime: new Date().toISOString() }); await Storage.setObject('currentUser', response.user); console.log('Login successful, session persisted'); return response.user; } // Logout and clear session async function logout(): Promise { await Storage.removeItem('authToken'); await Storage.removeItem('currentUser'); await Storage.removeItem('loginTime'); console.log('Logged out, session cleared'); } // Update user preferences async function updateTheme(theme: 'light' | 'dark'): Promise { await Storage.setItem('theme', theme); console.log(`Theme updated to ${theme}`); } // Usage const appState = initializeApp(); console.log('App state:', appState); // Output: App state: { isAuthenticated: false, user: null, theme: 'light' } ``` -------------------------------- ### Sync API for Data Storage Source: https://github.com/thereallo1026/expo-native-storage/blob/master/README.md Illustrates the synchronous API for immediate data storage operations with expo-native-storage. This API allows for direct, non-Promise-based interaction for storing strings, objects, and managing items. ```typescript import Storage from 'expo-native-storage'; // Store strings synchronously Storage.setItemSync('username', 'john_doe'); const username = Storage.getItemSync('username'); // 'john_doe' // Store objects synchronously Storage.setObjectSync('user', { name: 'John', age: 30, premium: true }); const user = Storage.getObjectSync('user'); // Remove items synchronously Storage.removeItemSync('username'); // Clear all synchronously Storage.clearSync(); ``` -------------------------------- ### Rebuild App for Native Module Linking Source: https://github.com/thereallo1026/expo-native-storage/blob/master/README.md Instructions for rebuilding the Expo application to link native modules, specifically when encountering the 'Cannot find native module' error. This involves cleaning the project and running platform-specific build commands. ```bash bunx expo prebuild --clean bunx expo run:ios # or run:android ``` -------------------------------- ### Store String Data with Async and Sync APIs Source: https://context7.com/thereallo1026/expo-native-storage/llms.txt Demonstrates how to store string values using both asynchronous (setItem) and synchronous (setItemSync) methods. The async version returns a Promise, suitable for non-blocking operations, while the sync version blocks until completion, ideal for initialization. ```typescript import Storage from 'expo-native-storage'; // Async: Store user authentication token await Storage.setItem('authToken', 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...'); await Storage.setItem('userId', '12345'); await Storage.setItem('theme', 'dark'); // Sync: Store settings during app initialization Storage.setItemSync('locale', 'en-US'); Storage.setItemSync('onboardingComplete', 'true'); Storage.setItemSync('lastLoginDate', new Date().toISOString()); ``` -------------------------------- ### Async API for Data Storage Source: https://github.com/thereallo1026/expo-native-storage/blob/master/README.md Demonstrates the asynchronous (Promise-based) API for storing, retrieving, and removing data using expo-native-storage. Supports storing strings and objects, with methods for individual items and clearing all storage. ```typescript import Storage from 'expo-native-storage'; // Store strings await Storage.setItem('username', 'john_doe'); const username = await Storage.getItem('username'); // 'john_doe' // Store objects await Storage.setObject('user', { name: 'John', age: 30, premium: true }); const user = await Storage.getObject('user'); // Remove items await Storage.removeItem('username'); // Clear all await Storage.clear(); ``` -------------------------------- ### Multi-Set API Source: https://context7.com/thereallo1026/expo-native-storage/llms.txt Asynchronously stores multiple key-value pairs in a single operation by providing an object. All values must be strings. ```APIDOC ## multiSet ### Description Store multiple key-value pairs at once by providing an object. All values must be strings. ### Method `multiSet` (async) ### Endpoint N/A (Local storage operations) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **Object** (object) - An object where keys are the storage keys and values are the string values to be stored. ``` -------------------------------- ### Multi-Get API Source: https://context7.com/thereallo1026/expo-native-storage/llms.txt Asynchronously retrieves multiple items from storage at once by providing an array of keys. Returns an object mapping keys to their values. ```APIDOC ## multiGet ### Description Retrieve multiple items at once by providing an array of keys. Returns an object mapping keys to their values (or null if not found). ### Method `multiGet` (async) ### Endpoint N/A (Local storage operations) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript import Storage from 'expo-native-storage'; async function loadMultipleSettings() { const settings = await Storage.multiGet(['theme', 'locale', 'fontSize']); console.log(settings.theme); // 'dark' console.log(settings.locale); // 'en-US' console.log(settings.fontSize); // null return settings; } ``` ### Response #### Success Response (200) - **Object** (object) - An object where keys are the requested storage keys and values are the corresponding stored string values or null if the key was not found. ``` -------------------------------- ### Retrieve Objects with Async and Sync APIs Source: https://context7.com/thereallo1026/expo-native-storage/llms.txt Demonstrates retrieving stored JavaScript objects using asynchronous (getObject) and synchronous (getObjectSync) methods. The library automatically deserializes JSON back into objects. TypeScript generics can be used for type safety. ```typescript import Storage from 'expo-native-storage'; // Define your types interface UserProfile { id: number; name: string; email: string; preferences: { notifications: boolean; newsletter: boolean; }; } interface ShoppingCart { items: Array<{ productId: string; quantity: number; price: number }>; total: number; lastUpdated: number; } // Async: Load typed user profile const user = await Storage.getObject('userProfile'); if (user) { console.log(`Welcome back, ${user.name}!`); console.log(`Notifications: ${user.preferences.notifications ? 'enabled' : 'disabled'}`); } // Output: Welcome back, John Doe! // Output: Notifications: enabled // Sync: Load cart on app start const cart = Storage.getObjectSync('shoppingCart'); if (cart && cart.items.length > 0) { console.log(`Cart has ${cart.items.length} items, total: $${cart.total}`); } // Output: Cart has 2 items, total: $109.97 ``` -------------------------------- ### Clear Caches for Troubleshooting Source: https://github.com/thereallo1026/expo-native-storage/blob/master/README.md Commands to clear various caches that might resolve native module linking issues. This includes clearing the Metro bundler cache and performing a full project reinstall. ```bash # clear Metro bundler cache bunx expo start -c # clear all caches rm -rf node_modules bun install # or npm install bunx expo prebuild --clean ``` -------------------------------- ### Store Objects with Async and Sync APIs Source: https://context7.com/thereallo1026/expo-native-storage/llms.txt Illustrates storing JavaScript objects using asynchronous (setObject) and synchronous (setObjectSync) methods. The library automatically serializes objects to JSON before storing them, allowing for complex data persistence. ```typescript import Storage from 'expo-native-storage'; // Async: Store complex user profile await Storage.setObject('userProfile', { id: 12345, name: 'John Doe', email: 'john@example.com', preferences: { notifications: true, newsletter: false }, createdAt: '2024-01-15T10:30:00Z' }); // Store app settings await Storage.setObject('appSettings', { darkMode: true, fontSize: 16, autoSave: true, syncInterval: 300 }); // Sync: Store cart data for offline persistence Storage.setObjectSync('shoppingCart', { items: [ { productId: 'SKU001', quantity: 2, price: 29.99 }, { productId: 'SKU002', quantity: 1, price: 49.99 } ], total: 109.97, lastUpdated: Date.now() }); ``` -------------------------------- ### Store Multiple Items Source: https://context7.com/thereallo1026/expo-native-storage/llms.txt Stores multiple key-value pairs in a single operation by providing an object. All values must be strings. Ideal for saving multiple settings, user preferences, or session data efficiently. ```typescript import Storage from 'expo-native-storage'; // Store multiple settings in one operation async function saveUserPreferences() { await Storage.multiSet({ theme: 'dark', locale: 'en-US', fontSize: '16', autoSave: 'true', lastUpdated: new Date().toISOString() }); console.log('All preferences saved'); } // Store session data after login async function saveSession(token: string, userId: string, expiresAt: Date) { await Storage.multiSet({ authToken: token, userId: userId, sessionExpires: expiresAt.toISOString(), loginTime: new Date().toISOString() }); console.log('Session data stored'); } // Batch update configuration await Storage.multiSet({ 'config.apiEndpoint': 'https://api.example.com', 'config.timeout': '10000', 'config.retryAttempts': '3', 'config.debugMode': 'false' }); ``` -------------------------------- ### Clear All Storage Data (Async/Sync) Source: https://context7.com/thereallo1026/expo-native-storage/llms.txt Removes all items from the storage namespace. Provides both asynchronous and synchronous methods. Use with caution as it clears the entire storage. Suitable for full data resets or on user account deletion. ```typescript import Storage from 'expo-native-storage'; // Async: Full data reset (e.g., factory reset feature) async function resetApp() { await Storage.clear(); console.log('All storage data has been cleared'); } // Sync: Clear all data during development/testing function devReset() { Storage.clearSync(); console.log('Storage cleared synchronously'); } // Example: Clear on user account deletion async function deleteAccount() { // First perform API call to delete account on server // await api.deleteAccount(); // Then clear all local data await Storage.clear(); console.log('Account deleted and local data cleared'); } ``` -------------------------------- ### Clear Storage API Source: https://context7.com/thereallo1026/expo-native-storage/llms.txt Methods to clear all items from storage, both asynchronously and synchronously. Use with caution. ```APIDOC ## clear / clearSync ### Description Remove all items from storage. Use with caution as this clears the entire storage namespace. ### Method `clear` (async), `clearSync` (sync) ### Endpoint N/A (Local storage operations) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript import Storage from 'expo-native-storage'; // Async example async function resetAllData() { await Storage.clear(); } // Sync example function devClearStorage() { Storage.clearSync(); } ``` ### Response #### Success Response (200) No explicit return value for success, operations complete without error. #### Response Example ```json // No JSON response for these operations ``` ``` -------------------------------- ### Remove Item API Source: https://context7.com/thereallo1026/expo-native-storage/llms.txt Provides methods to asynchronously or synchronously remove single items from storage using their keys. ```APIDOC ## removeItem / removeItemSync ### Description Remove a single item from storage by its key. ### Method `removeItem` (async), `removeItemSync` (sync) ### Endpoint N/A (Local storage operations) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript import Storage from 'expo-native-storage'; // Async example async function removeAuthToken() { await Storage.removeItem('authToken'); } // Sync example function removeTempFlag() { Storage.removeItemSync('temporaryFlag'); } ``` ### Response #### Success Response (200) No explicit return value for success, operations complete without error. #### Response Example ```json // No JSON response for these operations ``` ``` -------------------------------- ### Remove Item from Storage (Async/Sync) Source: https://context7.com/thereallo1026/expo-native-storage/llms.txt Removes a single item from storage using its key. Supports both asynchronous and synchronous operations. Useful for clearing specific data like user sessions or temporary flags. ```typescript import Storage from 'expo-native-storage'; // Async: Clear user session on logout async function logout() { await Storage.removeItem('authToken'); await Storage.removeItem('userId'); await Storage.removeItem('userProfile'); console.log('User logged out, session data cleared'); } // Sync: Remove specific setting Storage.removeItemSync('temporaryFlag'); Storage.removeItemSync('cachedSearchResults'); // Verify removal const token = await Storage.getItem('authToken'); console.log('Token after removal:', token); // Output: Token after removal: null ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.