### Complete MMKV Configuration Example Source: https://github.com/ammarahm-ed/react-native-mmkv-storage/blob/master/docs/loaderclass.md A comprehensive example showing how to chain multiple configuration methods and initialize the instance. ```javascript import { MMKVLoader } from "react-native-mmkv-storage"; let MMKV = new MMKVLoader() .withInstanceID('mmkvInstanceID') .setProcessingMode(MMKVStorage.MODES.MULTI_PROCESS) .withEncryption() .encryptWithCustomKey('encryptionKey', true, 'customAlias') .initialize(); await MMKV.setStringAsync("string", "string"); let string = await MMKV.getStringAsync("string"); ``` -------------------------------- ### MMKV Loader Example Source: https://github.com/ammarahm-ed/react-native-mmkv-storage/blob/master/docs/loaderclass.md An example demonstrating how to chain multiple MMKVLoader methods to configure and initialize an MMKV instance. ```APIDOC ## Putting it together Now you know about the loader class, lets create a MMKV Instance with an ID. ```js import { MMKVLoader } from "react-native-mmkv-storage"; MMKV = new MMKVLoader(). .withInstanceID('mmkvInstanceID') .setProcessingMode(MMKVStorage.MODES.MULTI_PROCESS) .withEncryption() .encryptWithCustomKey('encryptionKey',true, 'customAlias') .initialize() // then use it await MMKV.setStringAsync("string", "string"); let string = await MMKV.getStringAsync("string"); ``` ``` -------------------------------- ### Installation Source: https://github.com/ammarahm-ed/react-native-mmkv-storage/blob/master/docs/README.md Instructions for installing the react-native-mmkv-storage library. ```APIDOC ## Installation ### npm ```bash npm install react-native-mmkv-storage ``` ### Expo Bare Workflow ```bash expo prebuild ``` ``` -------------------------------- ### Install react-native-mmkv-storage Source: https://github.com/ammarahm-ed/react-native-mmkv-storage/blob/master/README.md Instructions for installing the react-native-mmkv-storage library using npm. For expo bare workflow, an additional prebuild step is required. ```bash npm install react-native-mmkv-storage ``` ```bash expo prebuild ``` -------------------------------- ### Implement Async Storage for Redux-Persist and Zustand Source: https://context7.com/ammarahm-ed/react-native-mmkv-storage/llms.txt Demonstrates how to initialize MMKV storage and implement the required interface for state persistence libraries. It includes examples for both async/await and callback patterns, and a full integration example for Zustand middleware. ```javascript import { MMKVLoader } from "react-native-mmkv-storage"; import { create } from "zustand"; import { persist } from "zustand/middleware"; const storage = new MMKVLoader().initialize(); // Async setItem and getItem examples await storage.setItem("persistKey", JSON.stringify({ user: "john" })); storage.setItem("key", "value", (error) => { if (error) console.error(error); }); const value = await storage.getItem("persistKey"); // Zustand persist integration const useStore = create( persist( (set) => ({ count: 0 }), { name: "my-storage", storage: { getItem: async (name) => { const value = await storage.getItem(name); return value ? JSON.parse(value) : null; }, setItem: async (name, value) => { await storage.setItem(name, JSON.stringify(value)); }, removeItem: async (name) => { storage.removeItem(name); } } } ) ); ``` -------------------------------- ### Install react-native-mmkv-storage using npm or yarn Source: https://github.com/ammarahm-ed/react-native-mmkv-storage/blob/master/docs/gettingstarted.md Installs the react-native-mmkv-storage library into your project using either npm or yarn package managers. ```bash npm install react-native-mmkv-storage ``` ```bash yarn add react-native-mmkv-storage ``` -------------------------------- ### Install Flipper and MMKV Plugin Source: https://github.com/ammarahm-ed/react-native-mmkv-storage/blob/master/docs/flipper.md Installs the necessary Flipper and MMKV storage plugins for React Native development using either Yarn or npm. This is a development dependency. ```bash yarn add react-native-flipper rn-mmkv-storage-flipper --dev ``` ```bash npm i react-native-flipper rn-mmkv-storage-flipper -D ``` -------------------------------- ### Install iOS Pods Source: https://github.com/ammarahm-ed/react-native-mmkv-storage/blob/master/docs/gettingstarted.md Installs the necessary CocoaPods dependencies for the iOS platform after adding the library to your project. ```bash pod install ``` -------------------------------- ### Creating Multiple MMKV Database Instances with Options (JavaScript) Source: https://github.com/ammarahm-ed/react-native-mmkv-storage/blob/master/README.md Illustrates how to create distinct MMKV database instances, each with its own configuration. This example shows creating a user data instance with encryption enabled and a separate settings instance. It utilizes the MMKVLoader class and its methods like withEncryption() and withInstanceID(). ```javascript const userStorage = new MMKVLoader().withEncryption().withInstanceID('userdata').initialize(); const settingsStorage = new MMKVLoader().withInstanceID('settings').initialize(); ``` -------------------------------- ### Initializing MMKV with Encryption Support (JavaScript) Source: https://github.com/ammarahm-ed/react-native-mmkv-storage/blob/master/README.md Shows the basic setup for initializing an MMKV storage instance with full encryption enabled. The .withEncryption() method automatically generates a secure key and stores it using the platform's secure storage (Keychain on iOS, Android Keystore on Android). ```javascript const storage = new MMKVLoader() .withEncryption() // Generates a random key and stores it securely in Keychain .initialize(); ``` -------------------------------- ### Set and Get String Async Source: https://github.com/ammarahm-ed/react-native-mmkv-storage/blob/master/docs/asyncapi.md Asynchronously sets and retrieves string values from MMKV storage using a given key. Returns a promise resolving to a boolean for set operations and a string for get operations. ```javascript await MMKV.setStringAsync("string", "string"); ``` ```javascript let string = await MMKV.getStringAsync("string"); ``` -------------------------------- ### Set and Get Array Async Source: https://github.com/ammarahm-ed/react-native-mmkv-storage/blob/master/docs/asyncapi.md Asynchronously sets and retrieves array values from MMKV storage using a given key. Returns a promise resolving to a boolean for set operations and an array for get operations. ```javascript let array = ["foo", "bar"]; await MMKV.setArrayAsync("array", array); ``` ```javascript let myArray = await MMKV.getArrayAsync("array"); ``` -------------------------------- ### Set and Get Integer Async Source: https://github.com/ammarahm-ed/react-native-mmkv-storage/blob/master/docs/asyncapi.md Asynchronously sets and retrieves number (integer) values from MMKV storage using a given key. Returns a promise resolving to a boolean for set operations and a number for get operations. ```javascript await MMKV.setIntAsync("number", 10); ``` ```javascript let number = await MMKV.getIntAsync("number"); ``` -------------------------------- ### Registering Lifecycle Functions with MMKV Transactions (JavaScript) Source: https://github.com/ammarahm-ed/react-native-mmkv-storage/blob/master/README.md Demonstrates how to register a 'beforewrite' lifecycle function for MMKV transactions. This example shows how to intercept write operations, check for a specific key prefix, and update a custom index based on the value's tag. It requires the MMKV library to be initialized. ```javascript MMKV.transactions.register('object', 'beforewrite', ({ key, value }) => { if (key.startsWith('post.')) { // Call this only when the key has the post prefix. let indexForTag = MMKV.getArray(`${value.tag}-index`) || []; MMKV.setArray(indexForTag.push(key)); } }); ``` -------------------------------- ### Get All Keys (Instance Indexer) Source: https://github.com/ammarahm-ed/react-native-mmkv-storage/blob/master/docs/queryingandindexing.md Retrieves all keys stored in the MMKV instance, regardless of their data type. Returns a promise that resolves to an array of strings. ```javascript let keys = await MMKV.indexer.getKeys(); ``` -------------------------------- ### Configure Docsify for react-native-mmkv-storage Source: https://github.com/ammarahm-ed/react-native-mmkv-storage/blob/master/docs/index.html Initializes the Docsify global configuration object. This setup defines navigation, search parameters, theme colors, and formatting rules for the documentation site. ```javascript window.$docsify = { auto2top: true, coverpage: true, executeScript: true, loadSidebar: true, mergeNavbar: false, maxLevel: 4, subMaxLevel: 2, name: 'react-native-mmkv-storage', themeColor: '#3399ff', textColor: '#333', search: { noData: { '/': 'No results!' }, paths: 'auto', placeholder: { '/': 'Search' } }, formatUpdated: '{MM}/{DD} {HH}:{mm}', themeable: { readyTransition: true, responsiveTables: true } }; ``` -------------------------------- ### Manage Boolean Values with MMKV Source: https://context7.com/ammarahm-ed/react-native-mmkv-storage/llms.txt Demonstrates how to store and retrieve boolean flags synchronously. Includes examples of direct retrieval and callback-based access. ```javascript import { MMKVLoader } from "react-native-mmkv-storage"; const storage = new MMKVLoader().initialize(); // Set boolean values storage.setBool("isLoggedIn", true); storage.setBool("darkMode", false); storage.setBool("notificationsEnabled", true); storage.setBool("hasCompletedOnboarding", true); // Get boolean values const isLoggedIn = storage.getBool("isLoggedIn"); // true const darkMode = storage.getBool("darkMode"); // false // Get with callback storage.getBool("notificationsEnabled", (error, value) => { if (!error) { console.log("Notifications:", value ? "enabled" : "disabled"); } }); // Returns null if key doesn't exist const missing = storage.getBool("nonexistent"); // null ``` -------------------------------- ### Redux Persist Integration Source: https://context7.com/ammarahm-ed/react-native-mmkv-storage/llms.txt Guide on using MMKV Storage as a high-performance replacement for AsyncStorage in Redux applications. ```APIDOC ## Redux Persist Integration ### Description MMKV can be used as a drop-in replacement for AsyncStorage within the redux-persist configuration to improve performance of state persistence. ### Configuration - **storage**: Pass the initialized MMKV instance to the persistConfig object. ### Usage Example ```javascript const persistConfig = { key: "root", storage: storage, whitelist: ["auth"] }; ``` ``` -------------------------------- ### Set and Get Map (Object) Async Source: https://github.com/ammarahm-ed/react-native-mmkv-storage/blob/master/docs/asyncapi.md Asynchronously sets and retrieves JavaScript objects (maps) from MMKV storage using a given key. Returns a promise resolving to a boolean for set operations and an object for get operations. ```javascript let myObject = { foo: "foo", bar: "bar" }; await MMKV.setMapAsync("myobject", myObject); ``` ```javascript let object = await MMKV.getMapAsync("object"); ``` -------------------------------- ### Perform Synchronous String Operations Source: https://context7.com/ammarahm-ed/react-native-mmkv-storage/llms.txt Shows how to store and retrieve string values synchronously. Includes examples of direct access and callback-based retrieval. ```javascript import { MMKVLoader } from "react-native-mmkv-storage"; const storage = new MMKVLoader().initialize(); storage.setString("username", "john_doe"); storage.setString("token", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."); const username = storage.getString("username"); const token = storage.getString("token"); storage.getString("username", (error, value) => { if (!error) { console.log("Username:", value); } }); const missing = storage.getString("nonexistent"); ``` -------------------------------- ### GET /indexer/arrays/all Source: https://github.com/ammarahm-ed/react-native-mmkv-storage/blob/master/docs/queryingandindexing.md Retrieves all array data stored within the MMKV storage system. ```APIDOC ## GET /indexer/arrays/all ### Description Fetches all arrays stored in the storage, returning them as a collection of key-value pairs. ### Method GET ### Endpoint MMKV.indexer.arrays.getAll() ### Response #### Success Response (200) - **data** (Promise) - An array of arrays where each inner array contains [key, data]. ### Response Example ```json [ ["key1", "data1"], ["key2", "data2"] ] ``` ``` -------------------------------- ### getMap Source: https://github.com/ammarahm-ed/react-native-mmkv-storage/blob/master/docs/callbackapi.md Gets an object from storage for a given key. ```APIDOC ## getMap ### Description Gets an object from storage for a given key. ### Method `MMKV.getMap(key: string, callback?: Function)` ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - **key** (String) - Required - The key of the object to retrieve. - **callback** (Function) - Optional - A callback function to be executed with the retrieved value. ### Request Example ```javascript let object = MMKV.getMap("object"); ``` ### Response #### Success Response (200) - **object** (Object) - The object value associated with the key. #### Response Example ```json { "foo": "foo", "bar": "bar" } ``` ``` -------------------------------- ### Perform Asynchronous Storage Operations Source: https://context7.com/ammarahm-ed/react-native-mmkv-storage/llms.txt Provides examples of using promise-based async variants for all storage types. Useful for non-blocking operations and batch loading data with Promise.all. ```javascript import { MMKVLoader } from "react-native-mmkv-storage"; const storage = new MMKVLoader().initialize(); // Example: Loading user data on app start async function loadUserData() { try { const [user, settings, isLoggedIn] = await Promise.all([ storage.getMapAsync("user"), storage.getMapAsync("settings"), storage.getBoolAsync("isLoggedIn") ]); return { user, settings, isLoggedIn }; } catch (error) { console.error("Failed to load user data:", error); return null; } } ``` -------------------------------- ### Store and Retrieve Strings Source: https://github.com/ammarahm-ed/react-native-mmkv-storage/blob/master/docs/callbackapi.md Methods to set and get string values from the MMKV storage using a specified key. ```javascript MMKV.setString("string", "string"); MMKV.getString("string"); ``` -------------------------------- ### Store and Retrieve Arrays Source: https://github.com/ammarahm-ed/react-native-mmkv-storage/blob/master/docs/callbackapi.md Methods to set and get array data structures from the MMKV storage. ```javascript let array = ["foo", "bar"]; MMKV.setArray("array", array); let retrievedArray = MMKV.getArray("array"); ``` -------------------------------- ### Get All String Keys (Strings Indexer) Source: https://github.com/ammarahm-ed/react-native-mmkv-storage/blob/master/docs/queryingandindexing.md Retrieves all keys that are associated with string data types in the MMKV storage. Returns a promise that resolves to an array of strings. ```javascript let keys = await MMKV.indexer.strings.getKeys(); ``` -------------------------------- ### Get All Boolean Keys (Booleans Indexer) Source: https://github.com/ammarahm-ed/react-native-mmkv-storage/blob/master/docs/queryingandindexing.md Retrieves all keys that are associated with boolean data types in the MMKV storage. Returns a promise that resolves to an array of strings. ```javascript let keys = await MMKV.indexer.booleans.getKeys(); ``` -------------------------------- ### Get All Number Keys (Numbers Indexer) Source: https://github.com/ammarahm-ed/react-native-mmkv-storage/blob/master/docs/queryingandindexing.md Retrieves all keys that are associated with number data types in the MMKV storage. Returns a promise that resolves to an array of strings. ```javascript let keys = await MMKV.indexer.numbers.getKeys(); ``` -------------------------------- ### Configure Jest for MMKV Storage Source: https://github.com/ammarahm-ed/react-native-mmkv-storage/blob/master/docs/mockjest.md This configuration snippet updates the Jest setup files and transform ignore patterns to ensure the MMKV storage library is correctly processed during testing. ```javascript module.exports = { preset: 'react-native', setupFiles: [ './node_modules/react-native-mmkv-storage/jest/mmkvJestSetup.js', ], transformIgnorePatterns: ['/!node_modules\/react-native-mmkv-storage/'], }; ``` -------------------------------- ### Initialize MMKV Storage Instances Source: https://context7.com/ammarahm-ed/react-native-mmkv-storage/llms.txt Demonstrates how to use the MMKVLoader builder pattern to create storage instances. Includes configurations for encryption, multi-process support, custom instance IDs, and performance tuning. ```javascript import { MMKVLoader, ProcessingModes, IOSAccessibleStates } from "react-native-mmkv-storage"; const storage = new MMKVLoader().initialize(); const userStorage = new MMKVLoader() .withInstanceID("userdata") .initialize(); const secureStorage = new MMKVLoader() .withInstanceID("secure") .withEncryption() .initialize(); const customEncrypted = new MMKVLoader() .withInstanceID("custom-encrypted") .withEncryption() .encryptWithCustomKey("mySecretKey123", true, "customKeyAlias") .initialize(); const sharedStorage = new MMKVLoader() .withInstanceID("shared") .setProcessingMode(ProcessingModes.MULTI_PROCESS) .initialize(); const iosStorage = new MMKVLoader() .withInstanceID("ios-secure") .withEncryption() .setAccessibleIOS(IOSAccessibleStates.WHEN_UNLOCKED) .withServiceName("com.myapp.storage") .initialize(); const persistedStorage = new MMKVLoader() .withPersistedDefaultValues() .initialize(); const fastStorage = new MMKVLoader() .disableIndexing() .initialize(); ``` -------------------------------- ### Initialize MMKV Instance Source: https://github.com/ammarahm-ed/react-native-mmkv-storage/blob/master/docs/loaderclass.md Demonstrates how to instantiate the MMKVLoader and initialize the storage instance. ```javascript import { MMKVLoader } from "react-native-mmkv-storage"; const MMKV = new MMKVLoader(); MMKV.initialize(); ``` -------------------------------- ### Initialize Default MMKV Instance Source: https://github.com/ammarahm-ed/react-native-mmkv-storage/blob/master/docs/creatinginstance.md Demonstrates how to import the MMKVLoader and initialize a default storage instance. It also shows basic asynchronous read and write operations. ```javascript import { MMKVLoader } from "react-native-mmkv-storage"; const MMKV = new MMKVLoader().initialize(); await MMKV.setStringAsync("string", "string"); let string = await MMKV.getStringAsync("string"); ``` -------------------------------- ### MMKVLoader Initialization Source: https://github.com/ammarahm-ed/react-native-mmkv-storage/blob/master/docs/loaderclass.md Demonstrates how to create a new MMKVLoader instance. ```APIDOC ## Create a Loader You can simply create a new Loader as follows: ```js import { MMKVLoader } from "react-native-mmkv-storage"; const MMKV = new MMKVLoader(); ``` ``` -------------------------------- ### Set and Get Boolean Async Source: https://github.com/ammarahm-ed/react-native-mmkv-storage/blob/master/docs/asyncapi.md Asynchronously sets and retrieves boolean values from MMKV storage using a given key. Returns a promise resolving to a boolean for both set and get operations. ```javascript await MMKV.setBoolAsync("myBooleanValue", false); ``` ```javascript let boolean = await MMKV.getBoolAsync("myBooleanValue"); ``` -------------------------------- ### MMKV Initialize Source: https://github.com/ammarahm-ed/react-native-mmkv-storage/blob/master/docs/loaderclass.md Initializes the MMKV instance with the selected properties and returns a usable MMKV instance. ```APIDOC ## initialize Initialize the MMKV Instance with the selected properties. Returns an MMKV Instance that you can use. ```js import { MMKVLoader } from "react-native-mmkv-storage"; const MMKV = new MMKVLoader(); MMKV.initialize(); ``` **Returns:** `API` ``` -------------------------------- ### Initialize Storage Instance Source: https://github.com/ammarahm-ed/react-native-mmkv-storage/blob/master/docs/README.md Create and initialize separate database instances for modular data management. ```APIDOC ## POST /storage/initialize ### Description Initializes a new MMKV storage instance with optional encryption and custom instance IDs. ### Method POST ### Endpoint new MMKVLoader().withInstanceID(id).initialize() ### Parameters #### Request Body - **instanceID** (string) - Required - Unique identifier for the database instance. - **encryption** (boolean) - Optional - Enable AES CFB-128 encryption. ### Request Example { "instanceID": "userdata", "withEncryption": true } ### Response #### Success Response (200) - **instance** (object) - The initialized storage instance. ``` -------------------------------- ### Initialize Storage Instance Source: https://github.com/ammarahm-ed/react-native-mmkv-storage/blob/master/README.md Create and initialize a new MMKV storage instance with optional encryption and custom IDs. ```APIDOC ## MMKVLoader.initialize ### Description Initializes a new storage instance. Can be configured with encryption and unique instance IDs. ### Method N/A (Constructor/Builder) ### Parameters - **withEncryption** (boolean) - Optional - Enables AES CFB-128 encryption. - **withInstanceID** (string) - Optional - Sets a unique identifier for the database instance. ### Request Example const storage = new MMKVLoader().withEncryption().withInstanceID('userdata').initialize(); ``` -------------------------------- ### Implement Custom Encryption Keys Source: https://github.com/ammarahm-ed/react-native-mmkv-storage/blob/master/docs/creatinginstance.md Demonstrates how to provide a custom encryption key for MMKV storage, with options to store the key securely and define a custom alias. ```javascript const MMKVwithEncryptionKey = new MMKVLoader().withEncryption().encryptWithCustomKey("encryptionKey").initialize(); const MMKVwithEncryptionKeySecure = new MMKVLoader().withEncryption().encryptWithCustomKey("encryptionKey", true).initialize(); const MMKVwithEncryptionKeyAlias = new MMKVLoader().withEncryption().encryptWithCustomKey("encryptionKey", true, "myCustomAlias").initialize(); ``` -------------------------------- ### getArray Source: https://github.com/ammarahm-ed/react-native-mmkv-storage/blob/master/docs/callbackapi.md Gets an array from storage for a given key. ```APIDOC ## getArray ### Description Gets an array from storage for a given key. ### Method `MMKV.getArray(key: string, callback?: Function)` ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - **key** (String) - Required - The key of the array to retrieve. - **callback** (Function) - Optional - A callback function to be executed with the retrieved value. ### Request Example ```javascript let array = MMKV.getArray("array"); ``` ### Response #### Success Response (200) - **Array<>** - The array value associated with the key. #### Response Example ```json ["foo", "bar"] ``` ``` -------------------------------- ### Initialize MMKVLoader Instance Source: https://github.com/ammarahm-ed/react-native-mmkv-storage/blob/master/docs/usemmkvref.md Shows the initialization of the MMKVLoader instance, which is required before using MMKV storage functionalities. ```javascript const MMKV = new MMKVLoader().initialize(); ``` -------------------------------- ### MMKV Initialization Source: https://github.com/ammarahm-ed/react-native-mmkv-storage/blob/master/docs/asyncapi.md Initializes the MMKV storage instance. This should be done once, typically when the application loads. ```APIDOC ## MMKV Initialization ### Description Initializes the MMKV storage instance. It's recommended to do this once when your application loads. ### Code Example ```javascript import { MMKVLoader } from "react-native-mmkv-storage"; const MMKV = new MMKVLoader().initialize(); ``` ``` -------------------------------- ### getBool Source: https://github.com/ammarahm-ed/react-native-mmkv-storage/blob/master/docs/callbackapi.md Gets a boolean value for a given key. ```APIDOC ## getBool ### Description Gets a boolean value for a given key. ### Method `MMKV.getBool(key: string, callback?: Function)` ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - **key** (String) - Required - The key of the boolean to retrieve. - **callback** (Function) - Optional - A callback function to be executed with the retrieved value. ### Request Example ```javascript MMKV.getBool("boolean"); ``` ### Response #### Success Response (200) - **boolean** (boolean) - The boolean value associated with the key. #### Response Example ```json true ``` ``` -------------------------------- ### getInt Source: https://github.com/ammarahm-ed/react-native-mmkv-storage/blob/master/docs/callbackapi.md Gets a number value for a given key. ```APIDOC ## getInt ### Description Gets a number value for a given key. ### Method `MMKV.getInt(key: string, callback?: Function)` ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - **key** (String) - Required - The key of the number to retrieve. - **callback** (Function) - Optional - A callback function to be executed with the retrieved value. ### Request Example ```javascript MMKV.getInt("number"); ``` ### Response #### Success Response (200) - **number** (number) - The number value associated with the key. #### Response Example ```json 10 ``` ``` -------------------------------- ### getString Source: https://github.com/ammarahm-ed/react-native-mmkv-storage/blob/master/docs/callbackapi.md Gets a string value for a given key. ```APIDOC ## getString ### Description Gets a string value for a given key. ### Method `MMKV.getString(key: string)` ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - **key** (String) - Required - The key of the string to retrieve. ### Request Example ```javascript MMKV.getString("string"); ``` ### Response #### Success Response (200) - **string** (string) - The string value associated with the key. #### Response Example ```json "string" ``` ``` -------------------------------- ### Integrate MMKV Storage with Flipper Source: https://github.com/ammarahm-ed/react-native-mmkv-storage/blob/master/docs/flipper.md Initializes the MMKV storage instance and conditionally enables Flipper integration within a development environment. This allows for live debugging of storage values. ```javascript import {MMKVLoader} from 'react-native-mmkv-storage'; import mmkvFlipper from 'rn-mmkv-storage-flipper'; const MMKV = new MMKVLoader() .withInstanceID('test') .withEncryption() .initialize(); if (__DEV__) { mmkvFlipper(MMKV); } ``` -------------------------------- ### GET /indexer/arrays/keys Source: https://github.com/ammarahm-ed/react-native-mmkv-storage/blob/master/docs/queryingandindexing.md Retrieves a list of all keys currently stored in the array indexer. ```APIDOC ## GET /indexer/arrays/keys ### Description Retrieves all keys associated with arrays stored in the MMKV indexer. ### Method GET ### Endpoint MMKV.indexer.arrays.getKeys() ### Response #### Success Response (200) - **keys** (Promise) - A promise that resolves to a boolean indicating the success of the retrieval operation. ### Request Example ```javascript let keys = await MMKV.indexer.arrays.getKeys(); ``` ``` -------------------------------- ### Initialize MMKV Instance with Unique ID Source: https://github.com/ammarahm-ed/react-native-mmkv-storage/blob/master/docs/creatinginstance.md Shows how to create multiple isolated MMKV storage instances by assigning a unique ID to each using the withInstanceID method. ```javascript const MMKVwithID = new MMKVLoader().withInstanceID("mmkvWithID").initialize(); await MMKVwithID.setStringAsync("string", "string"); let string = await MMKVwithID.getStringAsync("string"); ``` -------------------------------- ### Managing Encryption in MMKV Instances Source: https://context7.com/ammarahm-ed/react-native-mmkv-storage/llms.txt Covers initialization of encrypted storage, runtime encryption, decryption, and changing keys. It also demonstrates iOS-specific accessibility settings. ```javascript import { MMKVLoader, IOSAccessibleStates } from "react-native-mmkv-storage"; const encryptedStorage = new MMKVLoader().withEncryption().initialize(); const storage = new MMKVLoader().withInstanceID("mydata").initialize(); storage.encryption.encrypt(); storage.encryption.encrypt("mySecretPassword123", true); storage.encryption.encrypt("mySecretPassword123", true, "myCustomAlias"); storage.encryption.encrypt("mySecretPassword123", false); storage.encryption.encrypt("mySecretPassword123", true, "myAlias", IOSAccessibleStates.WHEN_UNLOCKED); storage.encryption.decrypt(); storage.encryption.changeEncryptionKey("newSecretPassword456", true); const { key, alias } = storage.getKey(); console.log("Encryption alias:", alias); ``` -------------------------------- ### Store and Retrieve Maps Source: https://github.com/ammarahm-ed/react-native-mmkv-storage/blob/master/docs/callbackapi.md Methods to set and get complex object structures (maps) from the MMKV storage. ```javascript let object = { foo: "foo", bar: "bar" }; MMKV.setMap("object", object); let retrievedObject = MMKV.getMap("object"); ``` -------------------------------- ### Initialize MMKV Instance Source: https://github.com/ammarahm-ed/react-native-mmkv-storage/blob/master/docs/generalmethods.md Initializes a default MMKV instance using the MMKVLoader class. This is the prerequisite step for performing any storage operations. ```javascript import { MMKVLoader } from "react-native-mmkv-storage"; MMKV = new MMKVLoader().initialize(); ``` -------------------------------- ### Store and Retrieve Booleans Source: https://github.com/ammarahm-ed/react-native-mmkv-storage/blob/master/docs/callbackapi.md Methods to set and get boolean values from the MMKV storage using a specified key. ```javascript MMKV.setBool("boolean", true); MMKV.getBool("boolean"); ``` -------------------------------- ### Initialize MMKV Storage Instance Source: https://github.com/ammarahm-ed/react-native-mmkv-storage/blob/master/docs/usemmkvstorage.md Initializes the MMKV storage instance using the MMKVLoader, which is required for all storage operations. ```javascript import { MMKVLoader } from "react-native-mmkv-storage"; const MMKV = new MMKVLoader().initialize(); ``` -------------------------------- ### Store and Retrieve Numbers Source: https://github.com/ammarahm-ed/react-native-mmkv-storage/blob/master/docs/callbackapi.md Methods to set and get numeric values from the MMKV storage using a specified key. ```javascript MMKV.setInt("number", 10); MMKV.getInt("number"); ``` -------------------------------- ### Initialize MMKV Storage for Redux Persist Source: https://github.com/ammarahm-ed/react-native-mmkv-storage/blob/master/docs/redux-persist.md This snippet shows how to import the MMKVLoader and initialize an instance to be used as the storage engine for redux-persist. ```javascript import { MMKVLoader } from "react-native-mmkv-storage"; const storage = new MMKVLoader().initialize(); ``` -------------------------------- ### Import MMKVLoader and useMMKVRef Hook Source: https://github.com/ammarahm-ed/react-native-mmkv-storage/blob/master/docs/usemmkvref.md Demonstrates how to import the necessary components from the react-native-mmkv-storage library. ```javascript import { MMKVLoader, useMMKVRef } from "react-native-mmkv-storage"; ``` -------------------------------- ### Managing Storage Instances and Metadata Source: https://context7.com/ammarahm-ed/react-native-mmkv-storage/llms.txt Provides utility methods for creating multiple storage instances, removing items, clearing caches, and retrieving instance metadata including encryption keys. ```javascript import { MMKVLoader } from "react-native-mmkv-storage"; const storage = new MMKVLoader() .withInstanceID("myapp") .initialize(); const userStorage = new MMKVLoader() .withInstanceID("userdata") .withEncryption() .initialize(); // Remove a single item storage.removeItem("username"); storage.removeItem("settings"); // Remove multiple items at once storage.removeItems(["key1", "key2", "key3"]); // Clear all data from the instance storage.clearStore(); // Clear memory cache (data remains on disk) storage.clearMemoryCache(); // Get all MMKV instance IDs ever created const allInstanceIds = storage.getAllMMKVInstanceIDs(); // Get currently loaded/initialized instance IDs const currentIds = storage.getCurrentMMKVInstanceIDs(); // Get encryption key info for encrypted instances const keyInfo = userStorage.getKey(); console.log("Alias:", keyInfo.alias); console.log("Key:", keyInfo.key); ``` -------------------------------- ### Use Create Helper for Storage Source: https://github.com/ammarahm-ed/react-native-mmkv-storage/blob/master/docs/usemmkvstorage.md Utilizes the create helper function to generate a pre-configured hook, reducing boilerplate code. ```javascript import { MMKVLoader, create } from "react-native-mmkv-storage"; const MMKV = new MMKVLoader().initialize(); export const useStorage = create(MMKV); ``` -------------------------------- ### Initialize MMKVStorage Instance Source: https://github.com/ammarahm-ed/react-native-mmkv-storage/blob/master/docs/transactionmanager.md Initializes the MMKVStorage instance. This is a prerequisite for using any of its functionalities. ```javascript import { MMKVLoader, useMMKVStorage } from 'react-native-mmkv-storage'; const MMKV = new MMKVLoader().initialize(); ``` -------------------------------- ### useMMKVStorage Hook Source: https://github.com/ammarahm-ed/react-native-mmkv-storage/blob/master/docs/README.md Demonstrates the usage of the useMMKVStorage hook for reactive data storage. ```APIDOC ## useMMKVStorage Hook ### Description The `useMMKVStorage` hook provides a reactive way to store and retrieve data. It automatically updates the UI when storage changes and persists data across app reloads. ### Usage ```javascript import { MMKVLoader, useMMKVStorage } from 'react-native-mmkv-storage'; const storage = new MMKVLoader().initialize(); const App = () => { const [user, setUser] = useMMKVStorage('user', storage, 'robert'); const [age, setAge] = useMMKVStorage('age', storage, 24); return ( I am {user} and I am {age} years old. ); }; ``` ### Parameters - **key** (string) - The key under which to store the data. - **storage** (MMKVLoader instance) - The MMKV storage instance. - **defaultValue** (any) - The default value to use if no data is found for the key. ### Returns - **[value, setValue]** (array) - A tuple containing the current value and a function to update it. ``` -------------------------------- ### Configuring redux-persist with MMKV Source: https://github.com/ammarahm-ed/react-native-mmkv-storage/blob/master/docs/redux-persist.md Steps to initialize an MMKV instance and integrate it into the redux-persist configuration object. ```APIDOC ## Integration: redux-persist with MMKV ### Description This integration allows developers to use the high-performance MMKV storage engine as the persistence layer for redux-persist, replacing the default AsyncStorage. ### Implementation Steps 1. Initialize the MMKV storage instance. 2. Assign the instance to the `storage` property in your `persistConfig` object. ### Code Example ```javascript import { MMKVLoader } from "react-native-mmkv-storage"; // Initialize storage const storage = new MMKVLoader().initialize(); // Configure redux-persist const persistConfig = { key: 'root', storage, }; ``` ### Requirements - **react-native-mmkv-storage**: Must be installed and linked in the project. - **redux-persist**: Must be configured in the Redux store setup. ``` -------------------------------- ### Configure Encrypted MMKV Instances Source: https://github.com/ammarahm-ed/react-native-mmkv-storage/blob/master/docs/creatinginstance.md Explains how to enable encryption for MMKV instances, which automatically handles key storage in the platform's secure keychain or keystore. ```javascript const MMKVwithEncryption = new MMKVLoader().withEncryption().initialize(); const MMKVwithEncryptionAndID = new MMKVLoader().withInstanceID("mmkvWithEncryptionAndID").withEncryption().initialize(); ``` -------------------------------- ### Get All Map Keys (Maps Indexer) Source: https://github.com/ammarahm-ed/react-native-mmkv-storage/blob/master/docs/queryingandindexing.md Retrieves all keys that are associated with map (object) data types in the MMKV storage. Returns a promise that resolves to an array of strings. ```javascript let keys = await MMKV.indexer.maps.getKeys(); ``` -------------------------------- ### Configure MMKV Core Library with Gradle Source: https://github.com/ammarahm-ed/react-native-mmkv-storage/blob/master/MMKV/Core/CMakeLists.txt This snippet configures the 'core' library for MMKV storage. It defines the library as static, lists all necessary C++ source and header files, and sets up include directories. It also includes platform-specific configurations for Windows and handles the zlib dependency. ```cmake add_library(core STATIC MMKV.h MMKV.cpp MMKV_Android.cpp MMKV_IO.h MMKV_IO.cpp MMKV_OSX.cpp MMKVLog.h MMKVLog.cpp MMKVLog_Android.cpp CodedInputData.h CodedInputData.cpp CodedInputData_OSX.cpp CodedInputDataCrypt.h CodedInputDataCrypt.cpp CodedInputDataCrypt_OSX.cpp CodedOutputData.h CodedOutputData.cpp KeyValueHolder.h KeyValueHolder.cpp PBUtility.h PBUtility.cpp MiniPBCoder.h MiniPBCoder.cpp MiniPBCoder_OSX.cpp MMBuffer.h MMBuffer.cpp InterProcessLock.h InterProcessLock.cpp InterProcessLock_Win32.cpp InterProcessLock_Android.cpp MemoryFile.h MemoryFile.cpp MemoryFile_Android.cpp MemoryFile_Linux.cpp MemoryFile_Win32.cpp MemoryFile_OSX.cpp ThreadLock.h ThreadLock.cpp ThreadLock_Win32.cpp MMKVMetaInfo.hpp aes/AESCrypt.h aes/AESCrypt.cpp aes/openssl/openssl_aes.h aes/openssl/openssl_aes_core.cpp aes/openssl/openssl_aes_locl.h aes/openssl/openssl_cfb128.cpp aes/openssl/openssl_opensslconf.h aes/openssl/openssl_md5_dgst.cpp aes/openssl/openssl_md5_locl.h aes/openssl/openssl_md5_one.cpp aes/openssl/openssl_md5.h aes/openssl/openssl_md32_common.h aes/openssl/openssl_arm_arch.h crc32/Checksum.h crc32/crc32_armv8.cpp crc32/zlib/zconf.h crc32/zlib/zutil.h crc32/zlib/crc32.h crc32/zlib/crc32.cpp MMKVPredef.h ) IF (MSVC OR (CMAKE_SYSTEM_PROCESSOR STREQUAL "x86_64")) # .S files is not supported by MSVC. # x86_64 asm not supported in OHOS ELSE() target_sources(core PRIVATE aes/openssl/openssl_aesv8-armx.S aes/openssl/openssl_aes-armv4.S) ENDIF() target_include_directories(core PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}) IF (WIN32) # MMKV can be used only with Unicode on Windows. target_compile_definitions(core PUBLIC UNICODE) target_compile_definitions(core PUBLIC _UNICODE) ENDIF() set_target_properties(core PROPERTIES CXX_STANDARD 20 CXX_EXTENSIONS OFF POSITION_INDEPENDENT_CODE ON ) find_library(zlib z ) IF (NOT zlib) target_compile_definitions(core PUBLIC MMKV_EMBED_ZLIB=1) ELSE() target_link_libraries(core ${zlib}) ENDIF() ``` -------------------------------- ### Get All Booleans (Booleans Indexer) Source: https://github.com/ammarahm-ed/react-native-mmkv-storage/blob/master/docs/queryingandindexing.md Retrieves all boolean data stored in MMKV. The result is an array of key-value pairs, where each pair is an array containing the key and its corresponding boolean data. ```javascript let booleans = await MMKV.indexer.booleans.getAll(); // Example structure: // [ // [key, data], // [key, data], // ]; ``` -------------------------------- ### Get All Numbers (Numbers Indexer) Source: https://github.com/ammarahm-ed/react-native-mmkv-storage/blob/master/docs/queryingandindexing.md Retrieves all number data stored in MMKV. The result is an array of key-value pairs, where each pair is an array containing the key and its corresponding number data. ```javascript let numbers = await MMKV.indexer.numbers.getAll(); // Example structure: // [ // [key, data], // [key, data], // ]; ``` -------------------------------- ### Check Key Existence (Instance Indexer) Source: https://github.com/ammarahm-ed/react-native-mmkv-storage/blob/master/docs/queryingandindexing.md Checks if a key exists across all data types in the MMKV storage using the instance indexer. Returns a promise that resolves to a boolean. ```javascript MMKV.indexer.hasKey("your key").then((result) => { if (result) { // if true do this. } else { // if false do this. } }); ``` -------------------------------- ### Get All Strings (Strings Indexer) Source: https://github.com/ammarahm-ed/react-native-mmkv-storage/blob/master/docs/queryingandindexing.md Retrieves all string data stored in MMKV. The result is an array of key-value pairs, where each pair is an array containing the key and its corresponding string data. ```javascript let strings = await MMKV.indexer.strings.getAll(); // Example structure: // [ // [key, data], // [key, data], // ]; ``` -------------------------------- ### Querying Data with Indexer API Source: https://context7.com/ammarahm-ed/react-native-mmkv-storage/llms.txt Demonstrates how to use the indexer API to retrieve keys and values grouped by their data type. This allows for efficient data management and filtering within the MMKV storage instance. ```javascript import { MMKVLoader } from "react-native-mmkv-storage"; const storage = new MMKVLoader().initialize(); // Store some data first storage.setString("name", "John"); storage.setString("email", "john@example.com"); storage.setInt("age", 30); storage.setInt("score", 100); storage.setBool("active", true); storage.setMap("profile", { bio: "Developer" }); storage.setArray("tags", ["react", "native"]); // Global indexer - all keys const allKeys = await storage.indexer.getKeys(); const hasName = storage.indexer.hasKey("name"); const hasMissing = storage.indexer.hasKey("nonexistent"); // Strings indexer const stringKeys = await storage.indexer.strings.getKeys(); const allStrings = await storage.indexer.strings.getAll(); // Numbers indexer const numberKeys = await storage.indexer.numbers.getKeys(); const allNumbers = await storage.indexer.numbers.getAll(); // Booleans indexer const boolKeys = await storage.indexer.booleans.getKeys(); const allBools = await storage.indexer.booleans.getAll(); // Objects (maps) indexer const mapKeys = await storage.indexer.maps.getKeys(); const allMaps = await storage.indexer.maps.getAll(); // Arrays indexer const arrayKeys = await storage.indexer.arrays.getKeys(); const allArrays = await storage.indexer.arrays.getAll(); ``` -------------------------------- ### Update Gradle Wrapper Version Source: https://github.com/ammarahm-ed/react-native-mmkv-storage/blob/master/docs/gettingstarted.md Modifies the `distributionUrl` in `android/gradle/wrapper/gradle-wrapper.properties` to specify the Gradle version required for SDK 30 and SDK 29. This is for manual installation on older React Native versions. ```diff distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-6.2-all.zip // When SDK 30 +distributionUrl=https\://services.gradle.org/distributions/gradle-6.9-all.zip // When SDK 29 +distributionUrl=https\://services.gradle.org/distributions/gradle-6.7-all.zip ``` -------------------------------- ### Implement useIndex hook in React Component Source: https://github.com/ammarahm-ed/react-native-mmkv-storage/blob/master/docs/useindex.md This example demonstrates how to initialize the useIndex hook within a functional component. It retrieves an array of objects based on an index and renders them using a FlatList. ```javascript const MyComponent = () => { const postsIndex = useMMKVStorage("postsIndex", MMKV, []); const [posts] = useIndex(postsIndex, "object", MMKV); return ( {item.title}} /> ); }; ``` -------------------------------- ### Get All Maps (Maps Indexer) Source: https://github.com/ammarahm-ed/react-native-mmkv-storage/blob/master/docs/queryingandindexing.md Retrieves all map (object) data stored in MMKV. The result is an array of key-value pairs, where each pair is an array containing the key and its corresponding object data. ```javascript let numbers = await MMKV.indexer.maps.getAll(); // Example structure: // [ // [key, data], // [key, data], // ]; ``` -------------------------------- ### Bulk Operations with MMKV Storage Source: https://context7.com/ammarahm-ed/react-native-mmkv-storage/llms.txt Demonstrates how to store and retrieve multiple items of various data types (object, number, boolean) simultaneously using `setMultipleItemsAsync` and `getMultipleItemsAsync`. It also shows the synchronous `getMultipleItems` method. ```javascript import { MMKVLoader } from "react-native-mmkv-storage"; const storage = new MMKVLoader().initialize(); // Set multiple items at once const users = [ ["user.1", { id: 1, name: "Alice" }], ["user.2", { id: 2, name: "Bob" }], ["user.3", { id: 3, name: "Charlie" }] ]; await storage.setMultipleItemsAsync(users, "object"); const scores = [ ["score.alice", 95], ["score.bob", 87], ["score.charlie", 92] ]; await storage.setMultipleItemsAsync(scores, "number"); const flags = [ ["feature.darkMode", true], ["feature.analytics", false], ["feature.notifications", true] ]; await storage.setMultipleItemsAsync(flags, "boolean"); // Get multiple items at once const userKeys = ["user.1", "user.2", "user.3"]; const allUsers = await storage.getMultipleItemsAsync(userKeys, "object"); // Returns: [["user.1", {id: 1, name: "Alice"}], ["user.2", {id: 2, name: "Bob"}], ...] const scoreKeys = ["score.alice", "score.bob", "score.charlie"]; const allScores = await storage.getMultipleItemsAsync(scoreKeys, "number"); // Returns: [["score.alice", 95], ["score.bob", 87], ["score.charlie", 92]] // Synchronous version const syncResults = storage.getMultipleItems(["user.1", "user.2"], "map"); ``` -------------------------------- ### Integrating MMKV with Redux Persist Source: https://context7.com/ammarahm-ed/react-native-mmkv-storage/llms.txt Shows how to configure redux-persist to use MMKV as a high-performance storage engine instead of the default AsyncStorage. This setup supports both plain and encrypted storage instances. ```javascript import { MMKVLoader } from "react-native-mmkv-storage"; import { persistStore, persistReducer } from "redux-persist"; import { createStore } from "redux"; const storage = new MMKVLoader().initialize(); const secureStorage = new MMKVLoader().withEncryption().initialize(); const persistConfig = { key: "root", storage: storage, whitelist: ["auth", "settings"], blacklist: ["navigation"] }; const rootReducer = (state = {}, action) => { switch (action.type) { case "SET_USER": return { ...state, user: action.payload }; default: return state; } }; const persistedReducer = persistReducer(persistConfig, rootReducer); const store = createStore(persistedReducer); const persistor = persistStore(store); import { Provider } from "react-redux"; import { PersistGate } from "redux-persist/integration/react"; function App() { return ( ); } ``` -------------------------------- ### Configure Instance ID Source: https://github.com/ammarahm-ed/react-native-mmkv-storage/blob/master/docs/loaderclass.md Sets a unique identifier for the MMKV instance, allowing multiple independent storage instances. ```javascript import { MMKVLoader } from "react-native-mmkv-storage"; let MMKV = new MMKVLoader(); MMKV = MMKV.withInstanceID("mmkvInstanceWithID"); ``` -------------------------------- ### Update Android Gradle Plugin and NDK Version Source: https://github.com/ammarahm-ed/react-native-mmkv-storage/blob/master/docs/gettingstarted.md Manually updates the Android Gradle plugin and NDK version in the `android/build.gradle` file for specific SDK versions (30 and 29). This is part of the manual installation process for older React Native versions. ```diff // When SDK 30 buildscript { build { compileSdkVersion = 30 targetSdkVersion = 30 + ndkVersion = "21.4.7075529" } dependencies { - classpath 'com.android.tools.build:gradle:3.2.0' + classpath 'com.android.tools.build:gradle:4.2.2' // When SDK 29 buildscript { build { compileSdkVersion = 29 targetSdkVersion = 29 + ndkVersion = "21.1.6352462" } dependencies { - classpath 'com.android.tools.build:gradle:3.2.0' + classpath 'com.android.tools.build:gradle:4.1.0' ```