### Install React Native Async Storage using npm or yarn Source: https://react-native-async-storage.github.io/3.0-next/index Installs the next version of the React Native Async Storage library using either npm or yarn package managers. This is the initial step before integrating the library into your project. ```bash # Using npm npm install @react-native-async-storage/async-storage@next # Using yarn yarn add @react-native-async-storage/async-storage@next ``` -------------------------------- ### Install iOS/macOS dependencies for Async Storage Source: https://react-native-async-storage.github.io/3.0-next/index Installs native dependencies for React Native Async Storage on iOS and macOS using CocoaPods. This command should be run within the `macos/ios` directory of your project to link the necessary native modules. ```bash # inside macos/ios directory pod install ``` -------------------------------- ### Web IndexedDB Database Name Example Source: https://react-native-async-storage.github.io/3.0-next/api/db-naming Shows how `databaseName` directly maps to the IndexedDB database name on the Web. While the underlying storage structure is abstracted, the `databaseName` ensures uniqueness for the IndexedDB instance. ```javascript const userId = "1234"; createAsyncStorage(`user-${userId}`); // Creates database named user-1234 ``` -------------------------------- ### Creating Isolated Storage Instances with AsyncStorage v3 Source: https://react-native-async-storage.github.io/3.0-next/migration-to-3 Demonstrates how to create separate, isolated storage instances in AsyncStorage v3. Each instance manages its own data, providing separation between different data sets within your application. This replaces the previous singleton pattern. ```javascript // create separate storages const userStorage = createAsyncStorage("user"); const cacheStorage = createAsyncStorage("cache"); ``` -------------------------------- ### Android Maven Repository Configuration for AsyncStorage Source: https://react-native-async-storage.github.io/3.0-next/migration-to-3 This snippet shows how to add a local Maven repository to your Android project's `build.gradle(.kts)` file. This is a requirement for AsyncStorage v3 on Android to locate necessary components. It involves adding a `maven` block with a specific URL to the `repositories` section. ```gradle allprojects { repositories { // ... others like google(), mavenCentral() maven { url = uri(project(":react-native-async-storage_async-storage").file("local_repo")) // or uri("path/to/node_modules/@react-native-async-storage/async-storage/android/local_repo") } } } ``` -------------------------------- ### Basic usage of React Native Async Storage Source: https://react-native-async-storage.github.io/3.0-next/index Demonstrates the fundamental operations of React Native Async Storage: creating a storage instance, setting an item with a key-value pair, retrieving the value associated with a key, and removing an item. This example utilizes the `createAsyncStorage`, `setItem`, `getItem`, and `removeItem` methods. ```javascript import { createAsyncStorage } from "@react-native-async-storage/async-storage"; // create a storage instance const storage = createAsyncStorage("appDB"); async function demo() { await storage.setItem("userToken", "abc123"); const token = await storage.getItem("userToken"); console.log("Stored token:", token); // abc123 await storage.removeItem("userToken"); } ``` -------------------------------- ### AsyncStorage v3 `multiSet` Renamed to `setMany` Source: https://react-native-async-storage.github.io/3.0-next/migration-to-3 Shows the updated method signature for setting multiple key-value pairs in AsyncStorage v3. The `multiSet` method is now called `setMany` and accepts entries as a `Record`, simplifying the input format for batch operations. ```typescript + setMany(entries: Record): Promise; ``` -------------------------------- ### AsyncStorage v3 `multiGet` Renamed to `getMany` Source: https://react-native-async-storage.github.io/3.0-next/migration-to-3 Illustrates the signature change for retrieving multiple keys in AsyncStorage v3. The `multiGet` method has been renamed to `getMany` and now returns a `Record`, providing a more predictable output where all requested keys are present in the result. ```typescript + getMany(keys: string[]): Promise>; ``` -------------------------------- ### iOS/macOS Database Path Example Source: https://react-native-async-storage.github.io/3.0-next/api/db-naming Demonstrates how `createAsyncStorage` uses a `databaseName` to construct the file path for the SQLite database on iOS and macOS. The database is placed within the app's Application Support directory, organized by `databaseName`. ```javascript const userId = "1234"; createAsyncStorage(`user-${userId}`); // creates: // /async-storage/databases/user-1234/user-1234.sqlite ``` -------------------------------- ### Android Database Path Example Source: https://react-native-async-storage.github.io/3.0-next/api/db-naming Illustrates the `databaseName` usage for database file paths on Android. Similar to Apple platforms, it creates a subdirectory within the app's internal files directory, named after the `databaseName`. ```javascript const userId = "1234"; createAsyncStorage(`user-${userId}`); // creates: // /async-storage/databases/user-1234/user-1234.sqlite ``` -------------------------------- ### Backward Compatible AsyncStorage Access (v2 Backend) Source: https://react-native-async-storage.github.io/3.0-next/migration-to-3 This code shows how the default export of AsyncStorage still points to the v2 implementation for smoother upgrades. This allows existing code using `AsyncStorage.setItem` to continue working, accessing previously stored data while enabling incremental migration to v3 instances. ```javascript // Still works (uses the v2 backend) import AsyncStorage from "@react-native-async-storage/async-storage"; await AsyncStorage.setItem("foo", "bar"); ``` -------------------------------- ### Clear AsyncStorage Storage Source: https://react-native-async-storage.github.io/3.0-next/api/usage Provides an example of how to remove all data from an AsyncStorage instance using the `clear` method. After clearing, `getAllKeys` will return an empty array, indicating that the storage is empty. ```javascript await userStorage.setMany({ email: "john@example.com", age: "30", }); await userStorage.clear(); const keys = await userStorage.getAllKeys(); console.log(keys); // [] ``` -------------------------------- ### AsyncStorage v3 `multiRemove` Renamed to `removeMany` Source: https://react-native-async-storage.github.io/3.0-next/migration-to-3 Details the renaming of the `multiRemove` method to `removeMany` in AsyncStorage v3. This method now takes an array of keys (`string[]`) to be removed from storage, offering a more straightforward API for batch deletion. ```typescript + removeMany(keys: string[]): Promise; ``` -------------------------------- ### iOS/macOS: Access SharedStorage with StorageRegistry in Brownfield Apps Source: https://react-native-async-storage.github.io/3.0-next/api/brownfield Illustrates how to access and utilize `SharedStorage` instances from native iOS/macOS code via the `StorageRegistry` singleton. This enables seamless data sharing between React Native and native environments in brownfield applications. The example includes setting and retrieving email entries. ```swift import AsyncStorage import SharedAsyncStorage // access shared storage via StorageRegistry let storage: SharedStorage = StorageRegistry.shared.getStorage(dbName: "my-users") Task { storage.setValues([Entry(key: "email", value: "john@example.com")]) let values = storage.getValues(keys: ["email"]) print("Stored email: (values.first?.value ?? "none")") } ``` -------------------------------- ### Recreated `useAsyncStorage` Hook for React Native Source: https://react-native-async-storage.github.io/3.0-next/migration-to-3 Provides a recreation of the removed `useAsyncStorage` hook for React Native. This hook offers convenient access to AsyncStorage methods like `getItem`, `setItem`, `mergeItem`, and `removeItem` based on a provided key. It's intended as a temporary solution until an improved version is reintroduced. ```typescript export function useAsyncStorage(key: string): AsyncStorageHook { return { getItem: (...args) => AsyncStorage.getItem(key, ...args), setItem: (...args) => AsyncStorage.setItem(key, ...args), mergeItem: (...args) => AsyncStorage.mergeItem(key, ...args), removeItem: (...args) => AsyncStorage.removeItem(key, ...args), }; } ``` -------------------------------- ### Configure Android local maven repo for Async Storage Source: https://react-native-async-storage.github.io/3.0-next/index Adds a local Maven repository to the `android/build.gradle(.kts)` file. This allows the Android build system to locate the Async Storage library, ensuring it's correctly linked during the build process. It specifies the URL for the local repository where the library artifacts are stored. ```gradle allprojects { repositories { // ... others like google(), mavenCentral() maven { url = uri(project(":react-native-async-storage_async-storage").file("local_repo")) // or uri("path/to/node_modules/@react-native-async-storage/async-storage/android/local_repo") } } } ``` -------------------------------- ### Create AsyncStorage Instance Source: https://react-native-async-storage.github.io/3.0-next/api/usage Demonstrates how to create a new, isolated storage instance using `createAsyncStorage`. Each instance is named to ensure scoped storage, which is independent of other instances. Note that Windows and visionOS do not support scoped storage and fall back to a single application-wide storage. ```javascript import { createAsyncStorage } from "@react-native-async-storage/async-storage"; const userStorage = createAsyncStorage("john"); ``` -------------------------------- ### Android: Access SharedStorage with StorageRegistry in Brownfield Apps Source: https://react-native-async-storage.github.io/3.0-next/api/brownfield Demonstrates how to access and use `SharedStorage` instances from native Android code using `StorageRegistry`. This is crucial for brownfield scenarios where React Native and native code need to share storage. It shows setting and retrieving values from a named storage instance. ```kotlin import android.content.Context import kotlinx.coroutines.runBlocking import org.asyncstorage.shared_storage.Entry import org.asyncstorage.shared_storage.SharedStorage import org.asyncstorage.storage.StorageRegistry // access shared storage via StorageRegistry val storage: SharedStorage = StorageRegistry.getStorage(ctx, "my-users") // runBlocking only for a demonstration runBlocking { storage.setValues(listOf(Entry("email", "john@example.com"))) val values = storage.getValues(listOf("email")) println("Stored email: ${values.firstOrNull()?.value}") } ``` -------------------------------- ### Retrieve All Keys with AsyncStorage Source: https://react-native-async-storage.github.io/3.0-next/api/usage Shows how to retrieve an array of all keys currently stored within an AsyncStorage instance using the `getAllKeys` method. This is useful for inspecting the contents of the storage. ```javascript await userStorage.setMany({ email: "john@example.com", age: "30", }); const keys = await userStorage.getAllKeys(); console.log(keys); // ["email", "age"] ``` -------------------------------- ### Single Item Operations with AsyncStorage Source: https://react-native-async-storage.github.io/3.0-next/api/usage Explains how to manage individual key-value pairs using `setItem`, `getItem`, and `removeItem`. `setItem` will overwrite existing values, while `removeItem` does not throw an error if the key is not found. `getItem` returns `null` if the key does not exist. ```javascript await userStorage.setItem("username", "doe_john"); // previously stored value is overriden await userStorage.setItem("username", "john_doe"); let username = await userStorage.getItem("username"); console.log(username); // "john_doe" await userStorage.removeItem("username"); // does nothing, item is already removed await userStorage.removeItem("username"); username = await userStorage.getItem("username"); console.log(username); // null ``` -------------------------------- ### Handle AsyncStorage Errors in JavaScript Source: https://react-native-async-storage.github.io/3.0-next/api/errors Demonstrates how to catch and handle AsyncStorageError exceptions in JavaScript. It checks the error type using a switch statement and logs specific messages for different error categories like SqliteStorageError and WebStorageError. ```javascript import { createAsyncStorage, AsyncStorageError, } from "@react-native-async-storage/async-storage"; const storage = createAsyncStorage("user"); try { await storage.setItem("email", "john@example.com"); } catch (e) { if (e instanceof AsyncStorageError) { switch (e.type) { case AsyncStorageError.Type.SqliteStorageError: console.error("SQLite failure:", e.message); break; case AsyncStorageError.Type.WebStorageError: console.error("IndexedDB failure:", e.message); break; default: console.error("AsyncStorage error:", e.message); } } else { console.error("Unexpected error:", e); } } ``` -------------------------------- ### Batch Operations with AsyncStorage Source: https://react-native-async-storage.github.io/3.0-next/api/usage Details how to perform multiple storage operations atomically using `setMany`, `getMany`, and `removeMany`. If any operation within a batch fails, none of the changes are applied. `getMany` returns `null` for non-existent keys, and `removeMany` ignores non-existent keys. ```javascript await userStorage.setMany({ email: "john@example.com", age: "30", }); const data = await userStorage.getMany(["email", "age", "username"]); console.log(data); // { // email: "john@example.com", // age: "30", // username: null, // key doesn't exist // } // non-existing keys are ignored await userStorage.removeMany(["email", "age", "not-here"]); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.