### Install @react-native-async-storage/async-storage Source: https://react-native-async-storage.github.io/latest Install the Async Storage package using either npm or yarn. Choose one command based on your package manager. ```bash # Using npm npm install @react-native-async-storage/async-storage # Using yarn yarn add @react-native-async-storage/async-storage ``` -------------------------------- ### Run pod install for iOS/macOS Source: https://react-native-async-storage.github.io/latest Install CocoaPods dependencies for iOS or macOS after adding the package. Run this command inside the ios or macos directory. ```bash # inside macos/ios directory pod install ``` -------------------------------- ### Use createAsyncStorage to store and retrieve a token Source: https://react-native-async-storage.github.io/latest Create a storage instance with createAsyncStorage and use setItem, getItem, and removeItem to manage a key-value pair. The example stores a user token, retrieves it, and logs it before removing it. ```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"); } ``` -------------------------------- ### Android: Access SharedStorage via StorageRegistry Source: https://react-native-async-storage.github.io/latest/integrations/brownfield Use StorageRegistry.getStorage(ctx, "my-users") to obtain a SharedStorage instance. Multiple calls with the same name return the same singleton. The example uses runBlocking for demonstration and shows setting and getting values. ```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}") } ``` -------------------------------- ### iOS/macOS: Access SharedStorage via StorageRegistry Source: https://react-native-async-storage.github.io/latest/integrations/brownfield Use StorageRegistry.shared.getStorage(dbName: "my-users") to obtain a SharedStorage instance. The example uses a Task to perform asynchronous operations and shows setting and getting values. ```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")") } ``` -------------------------------- ### Integrate with TanStack Query using createAsyncStoragePersister Source: https://react-native-async-storage.github.io/latest/faq TanStack Query's @tanstack/query-async-storage-persister expects a storage object with getItem, setItem, and removeItem. The v3 AsyncStorage instance matches this interface directly. Install @tanstack/query-async-storage-persister and @tanstack/react-query-persist-client separately. ```javascript import { createAsyncStorage } from "@react-native-async-storage/async-storage"; import { createAsyncStoragePersister } from "@tanstack/query-async-storage-persister"; import { QueryClient } from "@tanstack/react-query"; import { PersistQueryClientProvider } from "@tanstack/react-query-persist-client"; const queryClient = new QueryClient({ defaultOptions: { queries: { gcTime: 1000 * 60 * 60 * 24, // 24 hours }, }, }); const storage = createAsyncStorage("tanstack-query"); const persister = createAsyncStoragePersister({ storage }); export default function App() { return ( ); } ``` -------------------------------- ### iOS & macOS: createAsyncStorage with databaseName Source: https://react-native-async-storage.github.io/latest/api/db-naming On Apple platforms, storage is located in the Application Support directory. The databaseName is normalized into a file path with the .sqlite extension, and each databaseName creates its own subdirectory inside async-storage/databases. The example shows the resulting directory and file paths. ```plaintext /async-storage/databases// ``` ```plaintext /async-storage/databases//.sqlite ``` ```javascript const userId = "1234"; createAsyncStorage(`user-${userId}`); // creates: // /async-storage/databases/user-1234/user-1234.sqlite ``` -------------------------------- ### Android: createAsyncStorage with databaseName Source: https://react-native-async-storage.github.io/latest/api/db-naming On Android, databases are stored in the app's internal files directory. The databaseName is normalized into a file path with the .sqlite extension, and each databaseName creates its own subdirectory inside async-storage/databases. The example shows the resulting directory and file paths. ```plaintext /async-storage/databases// ``` ```plaintext /async-storage/databases//.sqlite ``` ```javascript const userId = "1234"; createAsyncStorage(`user-${userId}`); // creates: // /async-storage/databases/user-1234/user-1234.sqlite ``` -------------------------------- ### Web: createAsyncStorage with databaseName Source: https://react-native-async-storage.github.io/latest/api/db-naming On the Web, databaseName corresponds directly to the name of the IndexedDB database. The async-storage grouping is abstracted away, but the name remains unique across instances. The example creates a database named user-1234. ```javascript const userId = "1234"; createAsyncStorage(`user-${userId}`); ``` -------------------------------- ### multiGet renamed to getMany Source: https://react-native-async-storage.github.io/latest/migration-to-3 Shows the signature change from multiGet to getMany, which returns a Record and follows a 'what you request is what you get' rule. ```typescript - multiGet: ( - keys: readonly string[], - callback?: MultiGetCallback - ) => Promise; + getMany(keys: string[]): Promise>; ``` -------------------------------- ### Handle AsyncStorage errors with AsyncStorageError.Type Source: https://react-native-async-storage.github.io/latest/api/errors Use this snippet to catch errors from AsyncStorage methods and handle them based on the error type. It checks if the error is an AsyncStorageError and switches on the type to log specific messages for SQLite, IndexedDB, or other errors. The example uses createAsyncStorage to create a storage instance and setItem to demonstrate the try/catch pattern. ```typescript 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); } } ``` -------------------------------- ### Handle errors with AsyncStorageError and e.type Source: https://react-native-async-storage.github.io/latest/faq All AsyncStorage methods throw AsyncStorageError on failure. Use a try/catch block and inspect e.type to handle specific failure modes. See the Error handling guide for the full list of error types. ```javascript import { AsyncStorageError, createAsyncStorage, } from "@react-native-async-storage/async-storage"; const storage = createAsyncStorage("my-app"); try { await storage.setItem("key", "value"); } catch (e) { if (e instanceof AsyncStorageError) { console.error(`Storage error [${e.type}]: ${e.message}`); } } ``` -------------------------------- ### Use the v2-style singleton with default export Source: https://react-native-async-storage.github.io/latest/faq The default export is a backward-compatible v2 instance. It uses the same legacy API as v2, including multiGet, multiSet, etc. Prefer createAsyncStorage for new integrations. ```javascript import AsyncStorage from "@react-native-async-storage/async-storage"; await AsyncStorage.getItem("key"); ``` -------------------------------- ### getAllKeys Source: https://react-native-async-storage.github.io/latest/api/usage Retrieves all keys currently used in the storage instance. ```APIDOC ## getAllKeys ### Description Retrieves all keys currently used in the storage instance. ### Method getAllKeys ### Parameters None. ### Request Example ```js const keys = await userStorage.getAllKeys(); console.log(keys); // ["email", "age"] ``` ### Response Returns a Promise that resolves to an array of keys (strings). ``` -------------------------------- ### Create a scoped storage instance with createAsyncStorage Source: https://react-native-async-storage.github.io/latest/api/usage Creates a new storage instance with a unique database name. Avoid file extensions in the name (e.g., 'user.db'). ```javascript import { createAsyncStorage } from "@react-native-async-storage/async-storage"; const userStorage = createAsyncStorage("john"); ``` -------------------------------- ### Read all keys with getAllKeys Source: https://react-native-async-storage.github.io/latest/api/usage Retrieves all keys currently used in the storage instance. ```javascript await userStorage.setMany({ email: "john@example.com", age: "30", }); const keys = await userStorage.getAllKeys(); console.log(keys); // ["email", "age"] ``` -------------------------------- ### createAsyncStorage Source: https://react-native-async-storage.github.io/latest/api/usage Creates a new storage instance with a unique database name. Each instance has isolated data. ```APIDOC ## createAsyncStorage ### Description Creates a new storage instance with a unique database name. Each instance has isolated data. ### Method createAsyncStorage ### Parameters - **name** (string) - Required - Unique database name for the storage instance. ### Request Example ```js import { createAsyncStorage } from "@react-native-async-storage/async-storage"; const userStorage = createAsyncStorage("john"); ``` ### Response Returns a storage instance with methods for data operations. ``` -------------------------------- ### clear Source: https://react-native-async-storage.github.io/latest/api/usage Removes all data from a storage instance. ```APIDOC ## clear ### Description Removes all data from a storage instance. ### Method clear ### Parameters None. ### Request Example ```js await userStorage.clear(); ``` ### Response Returns a Promise that resolves when the operation completes. ``` -------------------------------- ### Clear storage with clear Source: https://react-native-async-storage.github.io/latest/api/usage Removes all data from the storage instance. ```javascript await userStorage.setMany({ email: "john@example.com", age: "30", }); await userStorage.clear(); const keys = await userStorage.getAllKeys(); console.log(keys); // [] ``` -------------------------------- ### Integrate with Zustand using createJSONStorage Source: https://react-native-async-storage.github.io/latest/faq Zustand's persist middleware accepts a custom storage adapter via createJSONStorage. Pass a factory function returning an AsyncStorage instance. createJSONStorage handles serialization, so you don't need to manually call JSON.stringify / JSON.parse. ```javascript import { create } from "zustand"; import { persist, createJSONStorage } from "zustand/middleware"; import { createAsyncStorage } from "@react-native-async-storage/async-storage"; const storage = createAsyncStorage("zustand"); interface BearState { bears: number; addBear: () => void; reset: () => void; } export const useBearStore = create()( persist( (set) => ({ bears: 0, addBear: () => set((state) => ({ bears: state.bears + 1 })), reset: () => set({ bears: 0 }), }), { name: "bear-storage", storage: createJSONStorage(() => storage), } ) ); ``` -------------------------------- ### Default export still works (v2 backend) Source: https://react-native-async-storage.github.io/latest/migration-to-3 The default export continues to reference the v2 implementation, allowing access to previously stored data and incremental migration. ```typescript // Still works (uses the v2 backend) import AsyncStorage from "@react-native-async-storage/async-storage"; await AsyncStorage.setItem("foo", "bar"); ``` -------------------------------- ### getMany Source: https://react-native-async-storage.github.io/latest/api/usage Retrieves multiple keys at once, returning null for any keys that don't exist. ```APIDOC ## getMany ### Description Retrieves multiple keys at once, returning null for any keys that don't exist. ### Method getMany ### Parameters - **keys** (array of strings) - Required - An array of keys to retrieve. ### Request Example ```js const data = await userStorage.getMany(["email", "age", "username"]); console.log(data); // { // email: "john@example.com", // age: "30", // username: null, // key doesn't exist // } ``` ### Response Returns a Promise that resolves to an object mapping keys to their values (or null for missing keys). ``` -------------------------------- ### Create separate storages with createAsyncStorage Source: https://react-native-async-storage.github.io/latest/migration-to-3 Creates isolated storage instances using createAsyncStorage, each representing a separate storage area for data separation. ```typescript // create separate storages const userStorage = createAsyncStorage("user"); const cacheStorage = createAsyncStorage("cache"); ``` -------------------------------- ### Batch operations: setMany, getMany, removeMany Source: https://react-native-async-storage.github.io/latest/api/usage Handles multiple keys atomically. setMany stores pairs, getMany returns null for missing keys, removeMany ignores non-existing 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"]); ``` -------------------------------- ### getItem Source: https://react-native-async-storage.github.io/latest/api/usage Retrieves the value for a given key. Returns null if the key does not exist. ```APIDOC ## getItem ### Description Retrieves the value for a given key. Returns null if the key does not exist. ### Method getItem ### Parameters - **key** (string) - Required - The key to retrieve. ### Request Example ```js let username = await userStorage.getItem("username"); console.log(username); // "john_doe" ``` ### Response Returns a Promise that resolves to the stored value (string) or null if the key does not exist. ``` -------------------------------- ### Old useAsyncStorage hook implementation Source: https://react-native-async-storage.github.io/latest/migration-to-3 The old useAsyncStorage hook, removed in v3, provided a wrapper around AsyncStorage methods for a given key. It will be reintroduced in a future release. ```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), }; } ``` -------------------------------- ### Integrate with Redux Persist using createAsyncStorage Source: https://react-native-async-storage.github.io/latest/faq The v3 AsyncStorage instance implements the storage interface Redux Persist expects (getItem, setItem, removeItem). Pass an instance directly as the storage option. The default export also works for gradual migration. ```javascript import { createAsyncStorage } from "@react-native-async-storage/async-storage"; import { persistReducer, persistStore } from "redux-persist"; import { combineReducers, createStore } from "redux"; const storage = createAsyncStorage("redux"); const persistConfig = { key: "root", storage, }; const rootReducer = combineReducers({ // your reducers }); const persistedReducer = persistReducer(persistConfig, rootReducer); const store = createStore(persistedReducer); const persistor = persistStore(store); ``` -------------------------------- ### Single item operations: setItem, getItem, removeItem Source: https://react-native-async-storage.github.io/latest/api/usage Stores, retrieves, and removes individual keys. setItem overwrites existing values; removeItem does nothing 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 ``` -------------------------------- ### Store objects and arrays with JSON.stringify and JSON.parse Source: https://react-native-async-storage.github.io/latest/faq AsyncStorage only stores strings. Serialize values with JSON.stringify before writing and JSON.parse when reading. ```javascript import { createAsyncStorage } from "@react-native-async-storage/async-storage"; const storage = createAsyncStorage("my-app"); // Storing an object const user = { name: "John", age: 30 }; await storage.setItem("user", JSON.stringify(user)); // Reading it back const raw = await storage.getItem("user"); const user = raw ? JSON.parse(raw) : null; ``` -------------------------------- ### setMany Source: https://react-native-async-storage.github.io/latest/api/usage Stores multiple key-value pairs atomically. Either all changes are applied, or none if an error occurs. ```APIDOC ## setMany ### Description Stores multiple key-value pairs atomically. Either all changes are applied, or none if an error occurs. ### Method setMany ### Parameters - **pairs** (object) - Required - An object containing key-value pairs to store. ### Request Example ```js await userStorage.setMany({ email: "john@example.com", age: "30", }); ``` ### Response Returns a Promise that resolves when the operation completes. ``` -------------------------------- ### multiSet renamed to setMany Source: https://react-native-async-storage.github.io/latest/migration-to-3 Shows the signature change from multiSet to setMany, which accepts a Record of key-value pairs. ```typescript - multiSet: ( - keyValuePairs: ReadonlyArray, - callback?: MultiCallback - ) => Promise; + setMany(entries: Record): Promise; ``` -------------------------------- ### setItem Source: https://react-native-async-storage.github.io/latest/api/usage Stores a key-value pair. Overwrites the current value if the key already exists. ```APIDOC ## setItem ### Description Stores a key-value pair. Overwrites the current value if the key already exists. ### Method setItem ### Parameters - **key** (string) - Required - The key to store. - **value** (string) - Required - The value to store. ### Request Example ```js await userStorage.setItem("username", "doe_john"); ``` ### Response Returns a Promise that resolves when the operation completes. ``` -------------------------------- ### removeMany Source: https://react-native-async-storage.github.io/latest/api/usage Deletes multiple keys; non-existing keys are ignored without errors. ```APIDOC ## removeMany ### Description Deletes multiple keys; non-existing keys are ignored without errors. ### Method removeMany ### Parameters - **keys** (array of strings) - Required - An array of keys to remove. ### Request Example ```js await userStorage.removeMany(["email", "age", "not-here"]); ``` ### Response Returns a Promise that resolves when the operation completes. ``` -------------------------------- ### multiRemove renamed to removeMany Source: https://react-native-async-storage.github.io/latest/migration-to-3 Shows the signature change from multiRemove to removeMany, which accepts a list of keys to remove. ```typescript - multiRemove: ( - keys: readonly string[], - callback?: MultiCallback - ) => Promise; + removeMany(keys: string[]): Promise; ``` -------------------------------- ### removeItem Source: https://react-native-async-storage.github.io/latest/api/usage Removes the value for a given key. Does nothing if the key does not exist. ```APIDOC ## removeItem ### Description Removes the value for a given key. Does nothing if the key does not exist. ### Method removeItem ### Parameters - **key** (string) - Required - The key to remove. ### Request Example ```js await userStorage.removeItem("username"); ``` ### Response Returns a Promise that resolves when the operation completes. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.