### Install Documentation Dependencies Source: https://github.com/react-native-async-storage/async-storage/blob/main/DEVELOPMENT.md Command to install Python dependencies for documentation using pip. ```shell pip install --no-deps -r .github/requirements.txt ``` -------------------------------- ### Installation Source: https://github.com/react-native-async-storage/async-storage/blob/main/docs/index.md Install the package using npm or yarn. ```shell # Using npm npm install @react-native-async-storage/async-storage # Using yarn yarn add @react-native-async-storage/async-storage ``` -------------------------------- ### Deploy Documentation Source: https://github.com/react-native-async-storage/async-storage/blob/main/DEVELOPMENT.md Commands to deploy documentation using 'mike', marking it as latest and pushing to the remote. ```shell mike deploy -u -r docs --push DOCS_VERSION_FROM_PCK_JSON latest mike set-default latest -r docs --push ``` -------------------------------- ### Usage Example Source: https://github.com/react-native-async-storage/async-storage/blob/main/docs/index.md Example of how to use Async Storage to set, get, and remove items. ```typescript 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"); } ``` -------------------------------- ### Fetch Documentation Branch Source: https://github.com/react-native-async-storage/async-storage/blob/main/DEVELOPMENT.md Command to fetch the 'gh-pages' branch from the 'docs' remote. ```shell git fetch docs gh-pages ``` -------------------------------- ### Install the plugin Source: https://github.com/react-native-async-storage/async-storage/blob/main/packages/expo-with-async-storage/README.md Install the expo-with-async-storage package using yarn. ```bash yarn add @react-native-async-storage/expo-with-async-storage ``` -------------------------------- ### Update Documentation Version Source: https://github.com/react-native-async-storage/async-storage/blob/main/DEVELOPMENT.md JSON snippet showing how to update the documentation version in the root package.json. ```json { "versionDocs": "3.0" } ``` -------------------------------- ### Add Documentation Remote Source: https://github.com/react-native-async-storage/async-storage/blob/main/DEVELOPMENT.md Command to add a new Git remote for hosting documentation, using SSH. ```shell # use https if not using ssh git remote add docs git@github.com:react-native-async-storage/react-native-async-storage.github.io.git ``` -------------------------------- ### iOS/macOS Pod Installation Source: https://github.com/react-native-async-storage/async-storage/blob/main/docs/index.md Install cocoapods dependencies for iOS and macOS. ```shell # inside macos/ios directory pod install ``` -------------------------------- ### Build Android Shared Storage SDK Source: https://github.com/react-native-async-storage/async-storage/blob/main/DEVELOPMENT.md Command to build the Android shared-storage SDK and publish it to the local Maven repository. ```shell yarn build:android ``` -------------------------------- ### Build Apple Shared Storage SDK Source: https://github.com/react-native-async-storage/async-storage/blob/main/DEVELOPMENT.md Command to build the shared-storage SDK for Apple platforms (iOS/macOS) as an xcframework. ```shell yarn build:apple ``` -------------------------------- ### AsyncStorage Clear Storage (TypeScript) Source: https://github.com/react-native-async-storage/async-storage/blob/main/docs/api/usage.md Provides an example of how to remove all data from an AsyncStorage instance using the `clear` method. This operation is irreversible and empties the entire storage for that instance. ```typescript await userStorage.setMany({ email: "john@example.com", age: "30", }); await userStorage.clear(); const keys = await userStorage.getAllKeys(); console.log(keys); // [] ``` -------------------------------- ### Create AsyncStorage Instance Source: https://github.com/react-native-async-storage/async-storage/blob/main/docs/api/usage.md Demonstrates how to create a new, isolated AsyncStorage instance using `createAsyncStorage`. Each instance is named and operates independently, except on platforms like Windows and visionOS which fall back to a single global instance. ```typescript import { createAsyncStorage } from "@react-native-async-storage/async-storage"; const userStorage = createAsyncStorage("john"); ``` -------------------------------- ### Use legacy v2 singleton API Source: https://github.com/react-native-async-storage/async-storage/blob/main/docs/faq.md Demonstrates how to use the default export for backward compatibility with v2-style singleton patterns. ```typescript import AsyncStorage from "@react-native-async-storage/async-storage"; await AsyncStorage.getItem("key"); ``` -------------------------------- ### Run Format Tests Source: https://github.com/react-native-async-storage/async-storage/blob/main/RELEASING.md Execute format tests to ensure code style consistency. ```shell yarn test:format ``` -------------------------------- ### Integrate AsyncStorage with Zustand Source: https://github.com/react-native-async-storage/async-storage/blob/main/docs/faq.md Shows how to use the Zustand persist middleware with a custom storage adapter via createJSONStorage. ```typescript 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), } ) ); ``` -------------------------------- ### Integrate AsyncStorage with TanStack Query Source: https://github.com/react-native-async-storage/async-storage/blob/main/docs/faq.md Demonstrates using an AsyncStorage instance with the TanStack Query persister to cache query data across app restarts. ```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, }, }, }); const storage = createAsyncStorage("tanstack-query"); const persister = createAsyncStoragePersister({ storage }); export default function App() { return ( ); } ``` -------------------------------- ### AsyncStorage Read All Keys (TypeScript) Source: https://github.com/react-native-async-storage/async-storage/blob/main/docs/api/usage.md Demonstrates how to retrieve an array of all keys currently present in an AsyncStorage instance using the `getAllKeys` method. This is useful for understanding the current state of the storage. ```typescript await userStorage.setMany({ email: "john@example.com", age: "30", }); const keys = await userStorage.getAllKeys(); console.log(keys); // ["email", "age"] ``` -------------------------------- ### Run Lint Tests Source: https://github.com/react-native-async-storage/async-storage/blob/main/RELEASING.md Execute lint tests for code quality checks. ```shell yarn test:lint ``` -------------------------------- ### Create manual mock file Source: https://github.com/react-native-async-storage/async-storage/blob/main/docs/integrations/jest.md Defines a manual mock file that Jest automatically uses to replace the native AsyncStorage implementation with the in-memory version. ```javascript module.exports = require("@react-native-async-storage/async-storage/jest"); ``` -------------------------------- ### Creating Separate Storage Instances Source: https://github.com/react-native-async-storage/async-storage/blob/main/docs/migration-to-3.md Demonstrates how to create distinct AsyncStorage instances for different data sets in v3. ```typescript createAsyncStorage("user"); createAsyncStorage("cache"); ``` -------------------------------- ### Accessing Shared Storage via StorageRegistry Source: https://github.com/react-native-async-storage/async-storage/blob/main/docs/integrations/brownfield.md Demonstrates how to retrieve a SharedStorage instance and perform read/write operations from native code. This ensures data consistency between the native layer and React Native. ```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 val storage: SharedStorage = StorageRegistry.getStorage(ctx, "my-users") runBlocking { storage.setValues(listOf(Entry("email", "john@example.com"))) val values = storage.getValues(listOf("email")) println("Stored email: ${values.firstOrNull()?.value}") } ``` ```swift import AsyncStorage import SharedAsyncStorage 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")") } ``` -------------------------------- ### Create Async Storage Instance with Database Name (TypeScript) Source: https://github.com/react-native-async-storage/async-storage/blob/main/docs/api/db-naming.md Demonstrates how to create a new AsyncStorage instance using a dynamic databaseName. This name is used to construct the file path for the underlying SQLite database on iOS and Android, and directly as the IndexedDB name on the Web. Each unique databaseName ensures data isolation between storage instances. ```typescript const userId = "1234"; createAsyncStorage(`user-${userId}`); ``` -------------------------------- ### Handle AsyncStorage errors Source: https://github.com/react-native-async-storage/async-storage/blob/main/docs/faq.md Demonstrates using try/catch blocks to handle AsyncStorageError instances and inspect specific error types. ```typescript 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}`); } } ``` -------------------------------- ### Run TypeScript Tests Source: https://github.com/react-native-async-storage/async-storage/blob/main/RELEASING.md Execute TypeScript tests for type checking. ```shell yarn test:ts ``` -------------------------------- ### AsyncStorage Batch Operations (TypeScript) Source: https://github.com/react-native-async-storage/async-storage/blob/main/docs/api/usage.md Shows how to perform multiple storage operations atomically using batch methods: `setMany` for storing multiple key-value pairs, `getMany` for retrieving multiple keys, and `removeMany` for deleting multiple keys. If any operation in a batch fails, none are applied. ```typescript 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"]); ``` -------------------------------- ### Integrate AsyncStorage with Redux Persist Source: https://github.com/react-native-async-storage/async-storage/blob/main/docs/faq.md Shows how to pass an AsyncStorage instance into the Redux Persist configuration to enable state persistence. ```typescript 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({}); const persistedReducer = persistReducer(persistConfig, rootReducer); const store = createStore(persistedReducer); const persistor = persistStore(store); ``` -------------------------------- ### Clear in-memory storage in tests Source: https://github.com/react-native-async-storage/async-storage/blob/main/docs/integrations/jest.md Demonstrates how to import and use the clearAllMockStorages utility to reset the in-memory state before each test execution. ```typescript import { clearAllMockStorages } from "@react-native-async-storage/async-storage/jest"; beforeEach(() => { clearAllMockStorages(); }); ``` -------------------------------- ### Handling AsyncStorage Errors Source: https://github.com/react-native-async-storage/async-storage/blob/main/docs/api/errors.md Demonstrates how to catch and categorize errors thrown by AsyncStorage methods using the AsyncStorageError class and its associated type enum. This pattern allows developers to implement specific logic based on whether the error originated from SQLite, Web storage, or other internal failures. ```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); } } ``` -------------------------------- ### multiGet Renamed to getMany Source: https://github.com/react-native-async-storage/async-storage/blob/main/docs/migration-to-3.md Illustrates the signature change from `multiGet` to `getMany` in v3, showing the new return type. ```diff multiGet: ( keys: readonly string[], callback?: MultiGetCallback ) => Promise; getMany(keys: string[]): Promise>; ``` -------------------------------- ### Continued Support for v2 Backend via Default Export Source: https://github.com/react-native-async-storage/async-storage/blob/main/docs/migration-to-3.md Shows that the default import still works with the v2 backend, facilitating incremental migration. ```typescript import AsyncStorage from "@react-native-async-storage/async-storage"; await AsyncStorage.setItem("foo", "bar"); ``` -------------------------------- ### Publish Shared Storage for Android to Maven Central Source: https://github.com/react-native-async-storage/async-storage/blob/main/RELEASING.md Release the Shared Storage for Android artifact to Maven Central. This involves updating the version, committing, and publishing the artifact using Gradle. ```shell ./gradlew :shared-storage:publishToMavenCentral --no-configuration-cache ``` -------------------------------- ### Add the plugin to app.json Source: https://github.com/react-native-async-storage/async-storage/blob/main/packages/expo-with-async-storage/README.md Configure your app.json to include the expo-with-async-storage plugin. ```json { "expo": { "plugins": [ "@react-native-async-storage/expo-with-async-storage" ] } } ``` -------------------------------- ### Re-implementation of `useAsyncStorage` Hook (v2) Source: https://github.com/react-native-async-storage/async-storage/blob/main/docs/migration-to-3.md Provides the v2 implementation of the `useAsyncStorage` hook, which was removed in v3 but may be needed for backward compatibility. ```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), }; } ``` -------------------------------- ### AsyncStorage Single Item Operations (TypeScript) Source: https://github.com/react-native-async-storage/async-storage/blob/main/docs/api/usage.md Illustrates the basic operations for managing individual key-value pairs in AsyncStorage: `setItem` to store or overwrite a value, `getItem` to retrieve a value, and `removeItem` to delete a key. Values are stored as strings. ```typescript 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 ``` -------------------------------- ### Serialize and store complex data in AsyncStorage Source: https://github.com/react-native-async-storage/async-storage/blob/main/docs/faq.md AsyncStorage only supports string values. This snippet demonstrates how to use JSON.stringify to store objects and JSON.parse to retrieve them. ```typescript 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; ``` -------------------------------- ### Apply inline mock for specific tests Source: https://github.com/react-native-async-storage/async-storage/blob/main/docs/integrations/jest.md Allows mocking AsyncStorage for a single test file by calling jest.mock at the top of the file, pointing to the built-in jest mock implementation. ```javascript jest.mock("@react-native-async-storage/async-storage", () => require("@react-native-async-storage/async-storage/jest") ); ``` -------------------------------- ### multiSet Renamed to setMany Source: https://github.com/react-native-async-storage/async-storage/blob/main/docs/migration-to-3.md Illustrates the signature change from `multiSet` to `setMany` in v3, showing the new input type. ```diff multiSet: ( keyValuePairs: ReadonlyArray, callback?: MultiCallback ) => Promise; setMany(entries: Record): Promise; ``` -------------------------------- ### Configure Jest transformIgnorePatterns Source: https://github.com/react-native-async-storage/async-storage/blob/main/docs/integrations/jest.md Configures Jest to correctly process the ESM source of the AsyncStorage package. This is required to prevent Jest from failing when encountering the package's source code. ```javascript transformIgnorePatterns: [ 'node_modules/(?!@react-native-async-storage/)', ], ``` -------------------------------- ### multiRemove Renamed to removeMany Source: https://github.com/react-native-async-storage/async-storage/blob/main/docs/migration-to-3.md Illustrates the signature change from `multiRemove` to `removeMany` in v3. ```diff multiRemove: ( keys: readonly string[], callback?: MultiCallback ) => Promise; removeMany(keys: string[]): Promise; ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.