Repository: mrousavy/react-native-mmkv Branch: main Commit: 3df2075e9f36 Files: 168 Total size: 319.3 KB Directory structure: gitextract_dgxiax_y/ ├── .clang-format ├── .github/ │ ├── FUNDING.yml │ ├── dependabot.yml │ └── workflows/ │ ├── build-android-release.yml │ ├── build-android.yml │ ├── build-ios-release.yml │ ├── build-ios.yml │ ├── harness-android.yml │ ├── harness-ios.yml │ ├── lint-cpp.yml │ ├── lint-typescript.yml │ ├── run-nitrogen.yml │ ├── test-js.yml │ └── update-lockfiles.yml ├── .gitignore ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── README_V3.md ├── babel.config.js ├── bunfig.toml ├── docs/ │ ├── HOOKS.md │ ├── LISTENERS.md │ ├── MIGRATE_FROM_ASYNC_STORAGE.md │ ├── V4_UPGRADE_GUIDE.md │ ├── WRAPPER_JOTAI.md │ ├── WRAPPER_MOBX.md │ ├── WRAPPER_MOBXPERSIST.md │ ├── WRAPPER_REACT_QUERY.md │ ├── WRAPPER_RECOIL.md │ ├── WRAPPER_REDUX.md │ ├── WRAPPER_TINYBASE.md │ └── WRAPPER_ZUSTAND_PERSIST_MIDDLEWARE.md ├── example/ │ ├── .eslintrc.js │ ├── .gitignore │ ├── .prettierrc.js │ ├── .watchmanconfig │ ├── Gemfile │ ├── README.md │ ├── __tests__/ │ │ └── MMKV.harness.ts │ ├── android/ │ │ ├── app/ │ │ │ ├── build.gradle │ │ │ ├── debug.keystore │ │ │ ├── proguard-rules.pro │ │ │ └── src/ │ │ │ └── main/ │ │ │ ├── AndroidManifest.xml │ │ │ ├── java/ │ │ │ │ └── com/ │ │ │ │ └── mrousavy/ │ │ │ │ └── mmkv/ │ │ │ │ └── example/ │ │ │ │ ├── MainActivity.kt │ │ │ │ └── MainApplication.kt │ │ │ └── res/ │ │ │ ├── drawable/ │ │ │ │ └── rn_edit_text_material.xml │ │ │ └── values/ │ │ │ ├── strings.xml │ │ │ └── styles.xml │ │ ├── build.gradle │ │ ├── gradle/ │ │ │ └── wrapper/ │ │ │ ├── gradle-wrapper.jar │ │ │ └── gradle-wrapper.properties │ │ ├── gradle.properties │ │ ├── gradlew │ │ ├── gradlew.bat │ │ └── settings.gradle │ ├── app.json │ ├── babel.config.js │ ├── index.js │ ├── ios/ │ │ ├── .xcode.env │ │ ├── MmkvExample/ │ │ │ ├── AppDelegate.swift │ │ │ ├── Images.xcassets/ │ │ │ │ ├── AppIcon.appiconset/ │ │ │ │ │ └── Contents.json │ │ │ │ └── Contents.json │ │ │ ├── Info.plist │ │ │ ├── LaunchScreen.storyboard │ │ │ └── PrivacyInfo.xcprivacy │ │ ├── MmkvExample.xcodeproj/ │ │ │ ├── project.pbxproj │ │ │ └── xcshareddata/ │ │ │ └── xcschemes/ │ │ │ └── MmkvExample.xcscheme │ │ ├── MmkvExample.xcworkspace/ │ │ │ └── contents.xcworkspacedata │ │ └── Podfile │ ├── jest.config.js │ ├── metro.config.js │ ├── package.json │ ├── rn-harness.config.mjs │ ├── src/ │ │ └── App.tsx │ └── tsconfig.json ├── jest.config.js ├── package.json ├── packages/ │ └── react-native-mmkv/ │ ├── .gitignore │ ├── .watchmanconfig │ ├── NitroMmkv.podspec │ ├── README.md │ ├── __bun_tests__/ │ │ └── use-jest-instead.test.ts │ ├── __mocks__/ │ │ └── react-native-nitro-modules.js │ ├── android/ │ │ ├── CMakeLists.txt │ │ ├── build.gradle │ │ ├── fix-prefab.gradle │ │ ├── gradle.properties │ │ └── src/ │ │ └── main/ │ │ ├── AndroidManifest.xml │ │ ├── cpp/ │ │ │ └── cpp-adapter.cpp │ │ └── java/ │ │ └── com/ │ │ └── margelo/ │ │ └── nitro/ │ │ └── mmkv/ │ │ ├── HybridMMKVPlatformContext.kt │ │ └── NitroMmkvPackage.java │ ├── babel.config.js │ ├── cpp/ │ │ ├── HybridMMKV.cpp │ │ ├── HybridMMKV.hpp │ │ ├── HybridMMKVFactory.cpp │ │ ├── HybridMMKVFactory.hpp │ │ ├── MMKVTypes.hpp │ │ ├── MMKVValueChangedListenerRegistry.cpp │ │ ├── MMKVValueChangedListenerRegistry.hpp │ │ └── ManagedMMBuffer.hpp │ ├── ios/ │ │ └── HybridMMKVPlatformContext.swift │ ├── nitro.json │ ├── nitrogen/ │ │ └── generated/ │ │ ├── .gitattributes │ │ ├── android/ │ │ │ ├── NitroMmkv+autolinking.cmake │ │ │ ├── NitroMmkv+autolinking.gradle │ │ │ ├── NitroMmkvOnLoad.cpp │ │ │ ├── NitroMmkvOnLoad.hpp │ │ │ ├── c++/ │ │ │ │ ├── JHybridMMKVPlatformContextSpec.cpp │ │ │ │ └── JHybridMMKVPlatformContextSpec.hpp │ │ │ └── kotlin/ │ │ │ └── com/ │ │ │ └── margelo/ │ │ │ └── nitro/ │ │ │ └── mmkv/ │ │ │ ├── HybridMMKVPlatformContextSpec.kt │ │ │ └── NitroMmkvOnLoad.kt │ │ ├── ios/ │ │ │ ├── NitroMmkv+autolinking.rb │ │ │ ├── NitroMmkv-Swift-Cxx-Bridge.cpp │ │ │ ├── NitroMmkv-Swift-Cxx-Bridge.hpp │ │ │ ├── NitroMmkv-Swift-Cxx-Umbrella.hpp │ │ │ ├── NitroMmkvAutolinking.mm │ │ │ ├── NitroMmkvAutolinking.swift │ │ │ ├── c++/ │ │ │ │ ├── HybridMMKVPlatformContextSpecSwift.cpp │ │ │ │ └── HybridMMKVPlatformContextSpecSwift.hpp │ │ │ └── swift/ │ │ │ ├── HybridMMKVPlatformContextSpec.swift │ │ │ └── HybridMMKVPlatformContextSpec_cxx.swift │ │ └── shared/ │ │ └── c++/ │ │ ├── Configuration.hpp │ │ ├── EncryptionType.hpp │ │ ├── HybridMMKVFactorySpec.cpp │ │ ├── HybridMMKVFactorySpec.hpp │ │ ├── HybridMMKVPlatformContextSpec.cpp │ │ ├── HybridMMKVPlatformContextSpec.hpp │ │ ├── HybridMMKVSpec.cpp │ │ ├── HybridMMKVSpec.hpp │ │ ├── Listener.hpp │ │ └── Mode.hpp │ ├── package.json │ ├── react-native.config.js │ ├── src/ │ │ ├── __tests__/ │ │ │ └── hooks.test.tsx │ │ ├── addMemoryWarningListener/ │ │ │ ├── addMemoryWarningListener.mock.ts │ │ │ ├── addMemoryWarningListener.ts │ │ │ └── addMemoryWarningListener.web.ts │ │ ├── createMMKV/ │ │ │ ├── createMMKV.ts │ │ │ ├── createMMKV.web.ts │ │ │ ├── createMockMMKV.ts │ │ │ └── getDefaultMMKVInstance.ts │ │ ├── deleteMMKV/ │ │ │ ├── deleteMMKV.ts │ │ │ └── deleteMMKV.web.ts │ │ ├── existsMMKV/ │ │ │ ├── existsMMKV.ts │ │ │ └── existsMMKV.web.ts │ │ ├── getMMKVFactory.ts │ │ ├── hooks/ │ │ │ ├── createMMKVHook.ts │ │ │ ├── useMMKV.ts │ │ │ ├── useMMKVBoolean.ts │ │ │ ├── useMMKVBuffer.ts │ │ │ ├── useMMKVKeys.ts │ │ │ ├── useMMKVListener.ts │ │ │ ├── useMMKVNumber.ts │ │ │ ├── useMMKVObject.ts │ │ │ └── useMMKVString.ts │ │ ├── index.ts │ │ ├── isTest.ts │ │ ├── specs/ │ │ │ ├── MMKV.nitro.ts │ │ │ ├── MMKVFactory.nitro.ts │ │ │ └── MMKVPlatformContext.nitro.ts │ │ └── web/ │ │ ├── createTextDecoder.ts │ │ ├── createTextEncoder.ts │ │ └── getLocalStorage.ts │ └── tsconfig.json └── scripts/ ├── clang-format.sh └── release.sh ================================================ FILE CONTENTS ================================================ ================================================ FILE: .clang-format ================================================ # Config for clang-format version 16 # Standard BasedOnStyle: llvm Standard: c++20 # Indentation IndentWidth: 2 ColumnLimit: 140 # Includes SortIncludes: CaseSensitive SortUsingDeclarations: true # Pointer and reference alignment PointerAlignment: Left ReferenceAlignment: Left ReflowComments: true # Line breaking options BreakBeforeBraces: Attach BreakConstructorInitializers: BeforeColon AlwaysBreakTemplateDeclarations: true AllowShortFunctionsOnASingleLine: Empty IndentCaseLabels: true NamespaceIndentation: Inner ================================================ FILE: .github/FUNDING.yml ================================================ # These are supported funding model platforms github: mrousavy patreon: # Replace with a single Patreon username open_collective: # Replace with a single Open Collective username ko_fi: mrousavy tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry liberapay: # Replace with a single Liberapay username issuehunt: # Replace with a single IssueHunt username otechie: # Replace with a single Otechie username custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] ================================================ FILE: .github/dependabot.yml ================================================ version: 2 updates: - package-ecosystem: "github-actions" directory: "/" schedule: interval: "weekly" labels: - "dependencies" - package-ecosystem: "gradle" directory: "/packages/react-native-mmkv/android/" schedule: interval: "weekly" labels: - "dependencies" ================================================ FILE: .github/workflows/build-android-release.yml ================================================ name: Build Android (Release) on: release: types: [published] pull_request: paths: - '.github/workflows/build-android-release.yml' jobs: build_release: name: Build Android Example App (release, new architecture) runs-on: ubuntu-latest steps: - uses: actions/checkout@v6 - uses: oven-sh/setup-bun@v2 - name: Install npm dependencies (bun) run: bun install - name: Install npm dependencies in example/ (bun) working-directory: example run: bun install - name: Setup JDK 17 uses: actions/setup-java@v5 with: distribution: 'zulu' java-version: 17 java-package: jdk - name: Run Gradle Build for example/android/ working-directory: example run: bun run build:android-release - name: Upload APK to Release uses: actions/upload-release-asset@v1 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} with: upload_url: ${{ github.event.release.upload_url }} asset_path: example/android/app/build/outputs/apk/release/app-release.apk asset_name: "MmkvExample-${{ github.event.release.tag_name }}.apk" asset_content_type: application/vnd.android.package-archive # Gradle cache doesn't like daemons - name: Stop Gradle Daemon working-directory: example/android run: ./gradlew --stop ================================================ FILE: .github/workflows/build-android.yml ================================================ name: Build Android on: push: branches: - main paths: - '.github/workflows/build-android.yml' - 'example/android/**' - '**/nitrogen/generated/shared/**' - '**/nitrogen/generated/android/**' - 'packages/react-native-mmkv/cpp/**' - 'packages/react-native-mmkv/android/**' - '**/bun.lock' - '**/react-native.config.js' - '**/nitro.json' pull_request: paths: - '.github/workflows/build-android.yml' - 'example/android/**' - '**/nitrogen/generated/shared/**' - '**/nitrogen/generated/android/**' - 'packages/react-native-mmkv/cpp/**' - 'packages/react-native-mmkv/android/**' - '**/bun.lock' - '**/react-native.config.js' - '**/nitro.json' jobs: build: name: Build Android Example App runs-on: ubuntu-latest steps: - uses: actions/checkout@v6 - uses: oven-sh/setup-bun@v2 - name: Install npm dependencies (bun) run: bun install - name: Setup JDK 17 uses: actions/setup-java@v5 with: distribution: 'zulu' java-version: 17 java-package: jdk - name: Restore Gradle cache uses: actions/cache@v5 with: path: | ~/.gradle/caches key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties') }} restore-keys: | ${{ runner.os }}-gradle- - name: Run Gradle Build for example/android/ working-directory: example/android run: ./gradlew assembleDebug --no-daemon --build-cache # Gradle cache doesn't like daemons - name: Stop Gradle Daemon working-directory: example/android run: ./gradlew --stop ================================================ FILE: .github/workflows/build-ios-release.yml ================================================ name: Build iOS (Release) on: release: types: [published] pull_request: paths: - '.github/workflows/build-ios-release.yml' jobs: build_release: name: Build iOS Example App (release, new architecture) runs-on: macos-latest steps: - uses: actions/checkout@v6 - uses: oven-sh/setup-bun@v2 - name: Install npm dependencies (bun) run: bun install - name: Install npm dependencies in example/ (bun) working-directory: example run: bun install - name: Setup Ruby (bundle) uses: ruby/setup-ruby@v1 with: ruby-version: 2.7.2 bundler-cache: true working-directory: example - name: Select Xcode 16.4 run: sudo xcode-select -s "/Applications/Xcode_16.4.app/Contents/Developer" - name: Restore Pods cache uses: actions/cache@v5 with: path: example/ios/Pods key: ${{ runner.os }}-pods-${{ hashFiles('**/Podfile.lock', '**/Gemfile.lock') }} restore-keys: | ${{ runner.os }}-pods- - name: Install Pods working-directory: example run: bun pods - name: Build App (Release, Simulator) working-directory: example/ios run: | set -o pipefail xcodebuild \ CC=clang CPLUSPLUS=clang++ LD=clang LDPLUSPLUS=clang++ \ -derivedDataPath build -UseModernBuildSystem=YES \ -workspace MmkvExample.xcworkspace \ -scheme MmkvExample \ -sdk iphonesimulator \ -configuration Release \ -destination 'generic/platform=iOS Simulator' \ build \ CODE_SIGNING_ALLOWED=NO - name: Package .app for Simulator run: | cd example/ios/build/Build/Products/Release-iphonesimulator zip -r ../../../../../../MmkvExample-Release-Simulator.zip MmkvExample.app - name: Upload .app to Release uses: actions/upload-release-asset@v1 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} with: upload_url: ${{ github.event.release.upload_url }} asset_path: MmkvExample-Release-Simulator.zip asset_name: "MmkvExample-Simulator-${{ github.event.release.tag_name }}.app.zip" asset_content_type: application/zip ================================================ FILE: .github/workflows/build-ios.yml ================================================ name: Build iOS on: push: branches: - main paths: - '.github/workflows/build-ios.yml' - 'example/ios/**' - '**/nitrogen/generated/shared/**' - '**/nitrogen/generated/ios/**' - 'packages/react-native-mmkv/cpp/**' - 'packages/react-native-mmkv/ios/**' - '**/Podfile.lock' - '**/*.podspec' - '**/react-native.config.js' - '**/nitro.json' pull_request: paths: - '.github/workflows/build-ios.yml' - 'example/ios/**' - '**/nitrogen/generated/shared/**' - '**/nitrogen/generated/ios/**' - 'packages/react-native-mmkv/cpp/**' - 'packages/react-native-mmkv/ios/**' - '**/Podfile.lock' - '**/*.podspec' - '**/react-native.config.js' - '**/nitro.json' env: USE_CCACHE: 1 # Must match the runner's architecture (macOS-15 runners are arm64) ARCH: arm64 jobs: build: name: Build iOS Example App runs-on: macOS-15 steps: - uses: actions/checkout@v6 - uses: oven-sh/setup-bun@v2 - name: Install npm dependencies (bun) run: bun install - name: Restore ccache uses: hendrikmuhs/ccache-action@v1.2 - name: Setup Ruby (bundle) uses: ruby/setup-ruby@v1 with: ruby-version: 2.7.2 bundler-cache: true working-directory: example - name: Select Xcode 16.4 run: sudo xcode-select -s "/Applications/Xcode_16.4.app/Contents/Developer" - name: Restore Pods cache uses: actions/cache@v5 with: path: example/ios/Pods key: ${{ runner.os }}-pods-${{ hashFiles('**/Podfile.lock', '**/Gemfile.lock') }} restore-keys: | ${{ runner.os }}-pods- - name: Install Pods working-directory: example run: bun pods - name: Build App working-directory: example/ios run: "set -o pipefail && xcodebuild \ CC=clang CPLUSPLUS=clang++ LD=clang LDPLUSPLUS=clang++ \ -derivedDataPath build -UseModernBuildSystem=YES \ -workspace MmkvExample.xcworkspace \ -scheme MmkvExample \ -sdk iphonesimulator \ -configuration Debug \ -destination 'generic/platform=iOS Simulator,arch=${{ env.ARCH }}' \ build \ CODE_SIGNING_ALLOWED=NO" ================================================ FILE: .github/workflows/harness-android.yml ================================================ name: Harness Android on: workflow_dispatch: inputs: device_api_level: description: "Android API level for the emulator" required: false default: "35" type: string device_arch: description: "Device architecture (x86_64, arm64-v8a)" required: false default: "x86_64" type: choice options: - x86_64 - arm64-v8a device_profile: description: "Device profile" required: false default: "pixel_7" type: string avd_name: description: "AVD name" required: false default: "Pixel_8_API_35" type: string push: branches: - main paths: - ".github/workflows/harness-android.yml" - "example/android/**" - "**/nitrogen/generated/shared/**" - "**/nitrogen/generated/android/**" - "packages/react-native-mmkv/cpp/**" - "packages/react-native-mmkv/android/**" - "**/bun.lock" - "**/react-native.config.js" - "**/nitro.json" - "example/__tests__/**" - "example/rn-harness.config.mjs" pull_request: paths: - ".github/workflows/harness-android.yml" - "example/android/**" - "**/nitrogen/generated/shared/**" - "**/nitrogen/generated/android/**" - "packages/react-native-mmkv/cpp/**" - "packages/react-native-mmkv/android/**" - "**/bun.lock" - "**/react-native.config.js" - "**/nitro.json" - "example/__tests__/**" - "example/rn-harness.config.mjs" env: # Device configuration - can be overridden by workflow_dispatch inputs DEVICE_API_LEVEL: ${{ github.event.inputs.device_api_level || '35' }} DEVICE_ARCH: ${{ github.event.inputs.device_arch || 'x86_64' }} DEVICE_PROFILE: ${{ github.event.inputs.device_profile || 'pixel_7' }} AVD_NAME: ${{ github.event.inputs.avd_name || 'Pixel_8_API_35' }} jobs: harness_android_new: name: Harness Android (new architecture) runs-on: ubuntu-latest steps: - uses: actions/checkout@v6 - uses: oven-sh/setup-bun@v2 - name: Install npm dependencies (bun) run: bun install - name: Setup JDK 17 uses: actions/setup-java@v5 with: distribution: "zulu" java-version: 17 java-package: jdk - name: Restore Gradle cache uses: actions/cache@v5 with: path: | ~/.gradle/caches key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties') }} restore-keys: | ${{ runner.os }}-gradle- - name: Build Android app working-directory: example/android run: ./gradlew assembleDebug --no-daemon --build-cache - name: Enable KVM group perms run: | echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS+="static_node=kvm"' | sudo tee /etc/udev/rules.d/99-kvm4all.rules sudo udevadm control --reload-rules sudo udevadm trigger --name-match=kvm ls /dev/kvm - name: AVD cache uses: actions/cache@v5 id: avd-cache with: path: | ~/.android/avd/* ~/.android/adb* key: avd-${{ env.DEVICE_API_LEVEL }}-${{ env.DEVICE_ARCH }} - name: Create AVD and generate snapshot for caching if: steps.avd-cache.outputs.cache-hit != 'true' uses: reactivecircus/android-emulator-runner@v2 with: api-level: ${{ env.DEVICE_API_LEVEL }} arch: ${{ env.DEVICE_ARCH }} profile: ${{ env.DEVICE_PROFILE }} disk-size: 1G heap-size: 1G force-avd-creation: false avd-name: ${{ env.AVD_NAME }} disable-animations: true emulator-options: -no-window -gpu swiftshader_indirect -noaudio -no-boot-anim -camera-back none script: echo "Generated AVD snapshot for caching." - name: Run Harness E2E tests uses: reactivecircus/android-emulator-runner@v2 with: working-directory: example api-level: ${{ env.DEVICE_API_LEVEL }} arch: ${{ env.DEVICE_ARCH }} force-avd-creation: false avd-name: ${{ env.AVD_NAME }} disable-animations: true emulator-options: -no-snapshot-save -no-window -gpu swiftshader_indirect -noaudio -no-boot-anim -camera-back none script: | adb install -r "./android/app/build/outputs/apk/debug/app-debug.apk" bun run test:harness --harnessRunner android # Gradle cache doesn't like daemons - name: Stop Gradle Daemon working-directory: example/android run: ./gradlew --stop ================================================ FILE: .github/workflows/harness-ios.yml ================================================ name: Harness iOS on: workflow_dispatch: inputs: device_model: description: "iOS Simulator device model" required: false default: "iPhone 16 Pro" type: string ios_version: description: "iOS version" required: false default: "18.6" type: string xcode_version: description: "Xcode version" required: false default: "16.4.0" type: string push: branches: - main paths: - ".github/workflows/harness-ios.yml" - "example/ios/**" - "**/nitrogen/generated/shared/**" - "**/nitrogen/generated/ios/**" - "packages/react-native-mmkv/cpp/**" - "packages/react-native-mmkv/ios/**" - "**/Podfile.lock" - "**/*.podspec" - "**/react-native.config.js" - "**/nitro.json" - "example/__tests__/**" - "example/rn-harness.config.mjs" pull_request: paths: - ".github/workflows/harness-ios.yml" - "example/ios/**" - "**/nitrogen/generated/shared/**" - "**/nitrogen/generated/ios/**" - "packages/react-native-mmkv/cpp/**" - "packages/react-native-mmkv/ios/**" - "**/Podfile.lock" - "**/*.podspec" - "**/react-native.config.js" - "**/nitro.json" - "example/__tests__/**" - "example/rn-harness.config.mjs" env: # Device configuration - can be overridden by workflow_dispatch inputs DEVICE_MODEL: ${{ github.event.inputs.device_model || 'iPhone 16 Pro' }} IOS_VERSION: ${{ github.event.inputs.ios_version || '18.6' }} XCODE_VERSION: ${{ github.event.inputs.xcode_version || '16.4.0' }} USE_CCACHE: 1 DEVELOPER_DIR: /Applications/Xcode_${{ github.event.inputs.xcode_version || '16.4.0' }}.app/Contents/Developer jobs: harness_ios_new: name: Harness iOS (new architecture) runs-on: macos-latest steps: - uses: actions/checkout@v6 - uses: oven-sh/setup-bun@v2 - name: Install npm dependencies (bun) run: bun install - name: Restore ccache uses: hendrikmuhs/ccache-action@v1.2 - name: Setup Ruby (bundle) uses: ruby/setup-ruby@v1 with: ruby-version: 2.7.2 bundler-cache: true working-directory: example - name: Select Xcode ${{ env.XCODE_VERSION }} run: sudo xcode-select -s "/Applications/Xcode_${{ env.XCODE_VERSION }}.app/Contents/Developer" - name: Restore Pods cache uses: actions/cache@v5 with: path: example/ios/Pods key: ${{ runner.os }}-pods-${{ hashFiles('**/Podfile.lock', '**/Gemfile.lock') }} restore-keys: | ${{ runner.os }}-pods- - name: Install Pods working-directory: example run: bun pods - name: Build iOS app working-directory: example/ios run: "set -o pipefail && xcodebuild \ CC=clang CPLUSPLUS=clang++ LD=clang LDPLUSPLUS=clang++ \ -derivedDataPath build -UseModernBuildSystem=YES \ -workspace MmkvExample.xcworkspace \ -scheme MmkvExample \ -sdk iphonesimulator \ -configuration Debug \ -destination 'platform=iOS Simulator,name=${{ env.DEVICE_MODEL }}' \ build \ CODE_SIGNING_ALLOWED=NO" - name: Setup iOS Simulator uses: futureware-tech/simulator-action@v5 with: model: ${{ env.DEVICE_MODEL }} os: iOS os_version: ${{ env.IOS_VERSION }} wait_for_boot: true erase_before_boot: false - name: Install app run: | xcrun simctl install booted example/ios/build/Build/Products/Debug-iphonesimulator/MmkvExample.app - name: Run Harness E2E tests working-directory: example run: | bun run test:harness --harnessRunner ios ================================================ FILE: .github/workflows/lint-cpp.yml ================================================ name: Validate C++ on: push: branches: - main paths: - '.github/workflows/lint-cpp.yml' - '**/*.h' - '**/*.hpp' - '**/*.cpp' - '**/*.c' - '**/*.mm' pull_request: paths: - '.github/workflows/lint-cpp.yml' - '**/*.h' - '**/*.hpp' - '**/*.cpp' - '**/*.c' - '**/*.mm' jobs: lint: name: Check clang-format runs-on: ubuntu-latest strategy: matrix: path: - 'packages/react-native-mmkv/android/src/main/cpp' - 'packages/react-native-mmkv/cpp' - 'packages/react-native-mmkv/ios' steps: - uses: actions/checkout@v6 - uses: oven-sh/setup-bun@v2 - name: Install npm dependencies (bun) run: bun install - name: Run clang-format style check uses: jidicula/clang-format-action@v4.17.0 with: clang-format-version: '18' check-path: ${{ matrix.path }} ================================================ FILE: .github/workflows/lint-typescript.yml ================================================ name: Lint TypeScript permissions: checks: write contents: read pull-requests: read on: push: branches: - main paths: - '.github/workflows/lint-typescript.yml' - 'config' - '**/*.ts' - '**/*.tsx' - '**/*.js' - '**/*.jsx' - '**/*.json' - '**/*.lockb' - '**/package.json' pull_request: paths: - '.github/workflows/lint-typescript.yml' - 'config' - '**/*.ts' - '**/*.tsx' - '**/*.js' - '**/*.jsx' - '**/*.json' - '**/*.lockb' - '**/package.json' jobs: tsc: name: Compile TypeScript (tsc) runs-on: ubuntu-latest steps: - uses: actions/checkout@v6 - uses: oven-sh/setup-bun@v2 - uses: reviewdog/action-setup@v1 - name: Install npm dependencies (bun) run: bun install - name: Run TypeScript (tsc) run: | bun typecheck | reviewdog -name="tsc" -efm="%f(%l,%c): error TS%n: %m" -reporter="github-pr-review" -filter-mode="nofilter" -fail-on-error -tee env: REVIEWDOG_GITHUB_API_TOKEN: ${{ secrets.GITHUB_TOKEN }} lint: name: Lint JS (eslint, prettier) runs-on: ubuntu-latest steps: - uses: actions/checkout@v6 - uses: oven-sh/setup-bun@v2 - uses: reviewdog/action-setup@v1 - name: Install npm dependencies (bun) run: bun install - name: Run ESLint CI in example/ working-directory: example run: bun lint-ci - name: Run ESLint CI in packages/react-native-mmkv working-directory: packages/react-native-mmkv run: bun lint-ci - name: Run ESLint with auto-fix in example/ working-directory: example run: bun lint - name: Run ESLint with auto-fix in packages/react-native-mmkv working-directory: packages/react-native-mmkv run: bun lint - name: Verify no files have changed after auto-fix run: git diff --exit-code HEAD -- . ':(exclude)bun.lock' ================================================ FILE: .github/workflows/run-nitrogen.yml ================================================ name: Run Nitrogen on: push: branches: - main paths: - '.github/workflows/run-nitrogen.yml' - '**/*.ts' - '**/*.tsx' - '**/*.js' - '**/*.jsx' - '**/*.json' - '**/*.lockb' - '**/nitro.json' - '**/package.json' pull_request: paths: - '.github/workflows/run-nitrogen.yml' - '**/*.ts' - '**/*.tsx' - '**/*.js' - '**/*.jsx' - '**/*.json' - '**/*.lockb' - '**/nitro.json' - '**/package.json' jobs: lint: name: Run Nitrogen for react-native-mmkv runs-on: ubuntu-latest steps: - uses: actions/checkout@v6 - uses: oven-sh/setup-bun@v2 - name: Install npm dependencies (bun) run: bun install - name: Build all packages run: bun mmkv build - name: Run nitrogen in packages/react-native-mmkv working-directory: packages/react-native-mmkv run: bun i && bun specs - name: Verify no files have changed after nitrogen run: git diff --exit-code HEAD -- . ':(exclude)bun.lock' ================================================ FILE: .github/workflows/test-js.yml ================================================ name: Test JS on: push: branches: - main paths: - '.github/workflows/test-js.yml' - 'packages/react-native-mmkv/**' pull_request: paths: - '.github/workflows/test-js.yml' - 'packages/react-native-mmkv/**' jobs: test: name: Test JS runs-on: ubuntu-latest steps: - uses: actions/checkout@v6 - uses: oven-sh/setup-bun@v2 - name: Install npm dependencies (bun) run: bun install - name: Run Jest run: bun run test ================================================ FILE: .github/workflows/update-lockfiles.yml ================================================ name: 'Update Lockfiles (bun.lock + Podfile.lock)' on: push: branches: - main paths: - ".github/workflows/update-lockfiles.yml" pull_request: paths: - ".github/workflows/update-lockfiles.yml" - "package.json" - "**/package.json" permissions: contents: write jobs: update-lockfiles: name: "Update lockfiles (Podfile.lock)" if: github.actor == 'dependabot[bot]' runs-on: macOS-latest steps: - uses: actions/checkout@v6 with: fetch-depth: 0 ref: ${{ github.event.pull_request.head.ref }} - uses: oven-sh/setup-bun@v2 - name: Setup Ruby (bundle) uses: ruby/setup-ruby@v1 with: ruby-version: 2.7.2 bundler-cache: true working-directory: example/ios - run: | bun install cd example bundle install bun pods cd .. cd docs bun install cd .. git add bun.lock git add example/ios/Podfile.lock git add example/Gemfile.lock git config --global user.name 'dependabot[bot]' git config --global user.email 'dependabot[bot]@users.noreply.github.com' git commit --amend --no-edit git push --force ================================================ FILE: .gitignore ================================================ .DS_Store **/node_modules/ # no yarn/npm in the root repo! /package-lock.json /yarn.lock .xcode.env.local .vscode # build .cache build compile_commands.json **/tsconfig.tsbuildinfo ================================================ FILE: CODE_OF_CONDUCT.md ================================================ # Contributor Covenant Code of Conduct ## Our Pledge We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, caste, color, religion, or sexual identity and orientation. We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. ## Our Standards Examples of behavior that contributes to a positive environment for our community include: * Demonstrating empathy and kindness toward other people * Being respectful of differing opinions, viewpoints, and experiences * Giving and gracefully accepting constructive feedback * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience * Focusing on what is best not just for us as individuals, but for the overall community Examples of unacceptable behavior include: * The use of sexualized language or imagery, and sexual attention or advances of any kind * Trolling, insulting or derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or email address, without their explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting ## Enforcement Responsibilities Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful. Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate. ## Scope This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at [INSERT CONTACT METHOD]. All complaints will be reviewed and investigated promptly and fairly. All community leaders are obligated to respect the privacy and security of the reporter of any incident. ## Enforcement Guidelines Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct: ### 1. Correction **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community. **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested. ### 2. Warning **Community Impact**: A violation through a single incident or series of actions. **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban. ### 3. Temporary Ban **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior. **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban. ### 4. Permanent Ban **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals. **Consequence**: A permanent ban from any sort of public interaction within the community. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.1, available at [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1]. Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder][Mozilla CoC]. For answers to common questions about this code of conduct, see the FAQ at [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at [https://www.contributor-covenant.org/translations][translations]. [homepage]: https://www.contributor-covenant.org [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html [Mozilla CoC]: https://github.com/mozilla/diversity [FAQ]: https://www.contributor-covenant.org/faq [translations]: https://www.contributor-covenant.org/translations ================================================ FILE: CONTRIBUTING.md ================================================ # Contributing Contributions are always welcome, no matter how large or small! We want this community to be friendly and respectful to each other. Please follow it in all your interactions with the project. Before contributing, please read the [code of conduct](./CODE_OF_CONDUCT.md). ## Development workflow To get started with the project, run `bun i` in the root directory to install the required dependencies for all packages & apps: ```sh bun i ``` The [example app](/example/) demonstrates usage of the library. You need to run it to test any changes you make. It is configured to use the local version of the library, so any changes you make to the library's source code will be reflected in the example app. Changes to the library's JavaScript code will be reflected in the example app without a rebuild, but native code changes will require a rebuild of the example app. If you want to use Android Studio or XCode to edit the native code, you can open the `example/android` or `example/ios` directories respectively in those editors. To edit the Objective-C or Swift files, open `example/ios/MmkvExample.xcworkspace` in XCode and find the source files at `Pods > Development Pods > react-native-mmkv`. To edit the Java or Kotlin files, open `example/android` in Android studio and find the source files at `react-native-mmkv` under `Android`. You can use various commands from the root directory to work with the project. To start the packager: ```sh bun example start ``` To run the example app on Android: ```sh bun example android ``` To run the example app on iOS: ```sh bun example ios ``` To confirm that the app is running with the new architecture, you can check the Metro logs for a message like this: ```sh Running "MmkvExample" with {"fabric":true,"initialProps":{"concurrentRoot":true},"rootTag":1} ``` Note the `"fabric":true` and `"concurrentRoot":true` properties. Make sure your code passes TypeScript and ESLint. Run the following to verify: ```sh bun typecheck bun lint ``` To fix formatting errors, run the following: ```sh bun lint --fix ``` Remember to add tests for your change if possible. Run the unit tests by: ```sh # `bun test` uses bun's test runner, which isn't compatible with flow notation # in RN. So use `bun run test` bun run test ``` ### Commit message convention We follow the [conventional commits specification](https://www.conventionalcommits.org/en) for our commit messages: - `fix`: bug fixes, e.g. fix crash due to deprecated method. - `feat`: new features, e.g. add new method to the module. - `refactor`: code refactor, e.g. migrate from class components to hooks. - `docs`: changes into documentation, e.g. add usage example for the module.. - `test`: adding or updating tests, e.g. add integration tests using detox. - `chore`: tooling changes, e.g. change CI config. Our pre-commit hooks verify that your commit message matches this format when committing. ### Linting and tests [ESLint](https://eslint.org/), [Prettier](https://prettier.io/), [TypeScript](https://www.typescriptlang.org/) We use [TypeScript](https://www.typescriptlang.org/) for type checking, [ESLint](https://eslint.org/) with [Prettier](https://prettier.io/) for linting and formatting the code, and [Jest](https://jestjs.io/) for testing. Our pre-commit hooks verify that the linter and tests pass when committing. ### Publishing to npm We use [release-it](https://github.com/release-it/release-it) to make it easier to publish new versions. It handles common tasks like bumping version based on semver, creating tags and releases etc. To publish new versions, run the following: ```sh bun release ``` ### Scripts The `package.json` file contains various scripts for common tasks: - `bun`: setup project by installing dependencies. - `bun typecheck`: type-check files with TypeScript. - `bun lint`: lint files with ESLint. - `bun test`: run unit tests with Jest. - `bun example start`: start the Metro server for the example app. - `bun example android`: run the example app on Android. - `bun example ios`: run the example app on iOS. ### Sending a pull request > **Working on your first pull request?** You can learn how from this _free_ series: [How to Contribute to an Open Source Project on GitHub](https://app.egghead.io/playlists/how-to-contribute-to-an-open-source-project-on-github). When you're sending a pull request: - Prefer small pull requests focused on one change. - Verify that linters and tests are passing. - Review the documentation to make sure it looks good. - Follow the pull request template when opening a pull request. - For pull requests that change the API or implementation, discuss with maintainers first by opening an issue. ================================================ FILE: LICENSE ================================================ MIT License Copyright (c) 2024 Marc Rousavy Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: README.md ================================================ | **V4 Docs** | [old V3 Docs](./README_V3.md) | |:---|:---| react-native-mmkv

MMKV

The fastest key/value storage for React Native.



This library helped you? Consider sponsoring!

* **MMKV** is an efficient, small mobile key-value storage framework developed by WeChat. See [Tencent/MMKV](https://github.com/Tencent/MMKV) for more information * **react-native-mmkv** is a library that allows you to easily use **MMKV** inside your React Native app through fast and direct JS bindings to the native C++ library. ## Features * **Get** and **set** strings, booleans, numbers and ArrayBuffers * **Fully synchronous** calls, no async/await, no Promises, no Bridge. * **Encryption** support (secure storage) * **Multiple instances** support (separate user-data with global data) * **Customizable storage location** * **High performance** because everything is **written in C++** * **~30x faster than AsyncStorage** * Uses [**JSI**](https://reactnative.dev/docs/the-new-architecture/landing-page#fast-javascriptnative-interfacing) and [**C++ NitroModules**](https://github.com/mrousavy/nitro) instead of the "old" Bridge * **iOS**, **Android** and **Web** support * Easy to use **React Hooks** API > [!IMPORTANT] > - **You're looking at MMKV V4. If you're still on V3, check out the [V3 docs here](./README_V3.md)**! > - react-native-mmkv **V4** is now a [Nitro Module](https://nitro.margelo.com). See the [V4 Upgrade Guide](./docs/V4_UPGRADE_GUIDE.md) for more information. ## Benchmark [StorageBenchmark](https://github.com/mrousavy/StorageBenchmark) compares popular storage libraries against each other by reading a value from storage for 1000 times:

MMKV vs other storage libraries: Reading a value from Storage 1000 times.
Measured in milliseconds on an iPhone 11 Pro, lower is better.

## Installation ### React Native ```sh npm install react-native-mmkv react-native-nitro-modules cd ios && pod install ``` ### Expo ```sh npx expo install react-native-mmkv react-native-nitro-modules npx expo prebuild ``` ## Usage ### Create a new instance To create a new instance of the MMKV storage, use the `MMKV` constructor. It is recommended that you re-use this instance throughout your entire app instead of creating a new instance each time, so `export` the `storage` object. #### Default ```ts import { createMMKV } from 'react-native-mmkv' export const storage = createMMKV() ``` This creates a new storage instance using the default MMKV storage ID (`mmkv.default`). #### App Groups or Extensions If you want to share MMKV data between your app and other apps or app extensions in the same group, open `Info.plist` and create an `AppGroupIdentifier` key with your app group's value. MMKV will then automatically store data inside the app group which can be read and written to from other apps or app extensions in the same group by making use of MMKV's multi processing mode. See [Configuring App Groups](https://developer.apple.com/documentation/xcode/configuring-app-groups). #### Customize ```ts import { createMMKV } from 'react-native-mmkv' export const storage = createMMKV({ id: `user-${userId}-storage`, path: `${USER_DIRECTORY}/storage`, encryptionKey: 'hunter2', encryptionType: 'AES-256', mode: 'multi-process', readOnly: false, compareBeforeSet: false, }) ``` This creates a new storage instance using a custom MMKV storage ID. By using a custom storage ID, your storage is separated from the default MMKV storage of your app. The following values can be configured: * `id`: The MMKV instance's ID. If you want to use multiple instances, use different IDs. For example, you can separate the global app's storage and a logged-in user's storage. (required if `path` or `encryptionKey` fields are specified, otherwise defaults to: `'mmkv.default'`) * `path`: The MMKV instance's root path. By default, MMKV stores file inside `$(Documents)/mmkv/`. You can customize MMKV's root directory on MMKV initialization (documentation: [iOS](https://github.com/Tencent/MMKV/wiki/iOS_advance#customize-location) / [Android](https://github.com/Tencent/MMKV/wiki/android_advance#customize-location)) * `encryptionKey`: The MMKV instance's encryption/decryption key. By default, MMKV stores all key-values in plain text on file, relying on iOS's/Android's sandbox to make sure the file is encrypted. Should you worry about information leaking, you can choose to encrypt MMKV. (documentation: [iOS](https://github.com/Tencent/MMKV/wiki/iOS_advance#encryption) / [Android](https://github.com/Tencent/MMKV/wiki/android_advance#encryption)) * `encryptionType`: The MMKV instance's encryption/decryption algorithm. By default, AES-128 encryption will be used, but you can switch to AES-256 for advanced security. * `mode`: The MMKV's process behaviour - when set to `multi-process`, the MMKV instance will assume data can be changed from the outside (e.g. App Clips, Extensions or App Groups). * `readOnly`: Whether this MMKV instance should be in read-only mode. This is typically more efficient and avoids unwanted writes to the data if not needed. Any call to `set(..)` will throw. * `compareBeforeSet`: Whether this MMKV instance will compare values for equality before writing them to disk. By default this is disabled, enabling it might improve performance if values are repeatedly written to disk, even if they are already persisted. ### Set ```ts storage.set('user.name', 'Marc') storage.set('user.age', 21) storage.set('is-mmkv-fast-asf', true) ``` ### Get ```ts const username = storage.getString('user.name') // 'Marc' const age = storage.getNumber('user.age') // 21 const isMmkvFastAsf = storage.getBoolean('is-mmkv-fast-asf') // true ``` ### Hooks ```ts const [username, setUsername] = useMMKVString('user.name') const [age, setAge] = useMMKVNumber('user.age') const [isMmkvFastAsf, setIsMmkvFastAsf] = useMMKVBoolean('is-mmkv-fast-asf') ``` ### Keys ```ts // checking if a specific key exists const hasUsername = storage.contains('user.name') // getting all keys const keys = storage.getAllKeys() // ['user.name', 'user.age', 'is-mmkv-fast-asf'] // delete a specific key + value const wasRemoved = storage.remove('user.name') // delete all keys storage.clearAll() ``` ### Objects ```ts const user = { username: 'Marc', age: 21 } // Serialize the object into a JSON string storage.set('user', JSON.stringify(user)) // Deserialize the JSON string into an object const jsonUser = storage.getString('user') // { 'username': 'Marc', 'age': 21 } const userObject = JSON.parse(jsonUser) ``` ### Encryption ```ts // encrypt all data with a private key using AES-128 storage.encrypt('hunter2') // encrypt all data with a private key using AES-256 storage.encrypt('hunter2again', 'AES-256') // remove encryption storage.decrypt() ``` ### Buffers ```ts const buffer = new ArrayBuffer(3) const dataWriter = new Uint8Array(buffer) dataWriter[0] = 1 dataWriter[1] = 100 dataWriter[2] = 255 storage.set('someToken', buffer) const buffer = storage.getBuffer('someToken') console.log(buffer) // [1, 100, 255] ``` ### Size ```ts // get size of MMKV storage in bytes const size = storage.size if (size >= 4096) { // clean unused keys and clear memory cache storage.trim() } ``` ### Importing all data from another MMKV instance To import all keys and values from another MMKV instance, use `importAllFrom(...)`: ```ts const storage = createMMKV(...) const otherStorage = createMMKV(...) const importedCount = storage.importAllFrom(otherStorage) ``` ### Check if an MMKV instance exists To check if an MMKV instance exists, use `existsMMKV(...)`: ```ts import { existsMMKV } from 'react-native-mmkv' const exists = existsMMKV('my-instance') ``` ### Delete an MMKV instance To delete an MMKV instance, use `deleteMMKV(...)`: ```ts import { deleteMMKV } from 'react-native-mmkv' const wasDeleted = deleteMMKV('my-instance') ``` ### Log Level By default, MMKV logs at `Debug` level in debug builds and `Warning` level in release builds. You can override this at build time to control the verbosity of MMKV's native logs. | Value | Level | |-------|-------| | 0 | Debug | | 1 | Info | | 2 | Warning | | 3 | Error | | 4 | None | #### Android Set `MMKV_logLevel` in your app's `android/gradle.properties`: ```properties MMKV_logLevel=4 ``` #### iOS Set `$MMKVLogLevel` in your app's `ios/Podfile`, then run `pod install`: ```ruby $MMKVLogLevel = 4 ``` Or use an environment variable during `pod install`: ```sh MMKV_LOG_LEVEL=4 pod install ``` ## Testing with Jest or Vitest A mocked MMKV instance is automatically used when testing with Jest or Vitest, so you will be able to use `createMMKV()` as per normal in your tests. Refer to [`example/__tests__/MMKV.harness.ts`](example/__tests__/MMKV.harness.ts) for an example using Jest. ## Documentation * [Hooks](./docs/HOOKS.md) * [Value-change Listeners](./docs/LISTENERS.md) * [Migrate from AsyncStorage](./docs/MIGRATE_FROM_ASYNC_STORAGE.md) * [Using MMKV with redux-persist](./docs/WRAPPER_REDUX.md) * [Using MMKV with recoil](./docs/WRAPPER_RECOIL.md) * [Using MMKV with mobx-persist-storage](./docs/WRAPPER_MOBX.md) * [Using MMKV with mobx-persist](./docs/WRAPPER_MOBXPERSIST.md) * [Using MMKV with zustand persist-middleware](./docs/WRAPPER_ZUSTAND_PERSIST_MIDDLEWARE.md) * [Using MMKV with jotai](./docs/WRAPPER_JOTAI.md) * [Using MMKV with react-query](./docs/WRAPPER_REACT_QUERY.md) * [Using MMKV with Tinybase](./docs/WRAPPER_TINYBASE.md) * [How is this library different from **react-native-mmkv-storage**?](https://github.com/mrousavy/react-native-mmkv/issues/100#issuecomment-886477361) ## LocalStorage and In-Memory Storage (Web) If a user chooses to disable LocalStorage in their browser, the library will automatically provide a limited in-memory storage as an alternative. However, this in-memory storage won't persist data, and users may experience data loss if they refresh the page or close their browser. To optimize user experience, consider implementing a suitable solution within your app to address this scenario. ## Limitations - react-native-mmkv V4 requires react-native 0.74 or higher. - react-native-mmkv V4 requires [the new architecture](https://reactnative.dev/docs/the-new-architecture/landing-page)/TurboModules to be enabled. - Since react-native-mmkv uses JSI for synchronous native method invocations, remote debugging (e.g. with Chrome) is no longer possible. Instead, you should use [Flipper](https://fbflipper.com) or [React DevTools](https://react.dev/learn/react-developer-tools). ## Integrations ### Rozenite Use [@rozenite/mmkv-plugin](https://www.rozenite.dev/docs/official-plugins/mmkv) to debug your MMKV storage using Rozenite. ### Reactotron Use [reactotron-react-native-mmkv](https://www.npmjs.com/package/reactotron-react-native-mmkv) to automatically log writes to your MMKV storage using Reactotron. [See the docs for how to setup this plugin with Reactotron.](https://www.npmjs.com/package/reactotron-react-native-mmkv) ## Community Discord [**Join the Margelo Community Discord**](https://margelo.com/discord) to chat about react-native-mmkv or other Margelo libraries. ## Adopting at scale react-native-mmkv is provided _as is_, I work on it in my free time. If you're integrating react-native-mmkv in a production app, consider [funding this project](https://github.com/sponsors/mrousavy) and contact me to receive premium enterprise support, help with issues, prioritize bugfixes, request features, help at integrating react-native-mmkv, and more. ## Contributing See the [contributing guide](CONTRIBUTING.md) to learn how to contribute to the repository and the development workflow. ## License MIT ================================================ FILE: README_V3.md ================================================ | [V4 Docs](./README.md) | **old V3 Docs** | |:---|:---| react-native-mmkv

MMKV

The fastest key/value storage for React Native.



This library helped you? Consider sponsoring!

* **MMKV** is an efficient, small mobile key-value storage framework developed by WeChat. See [Tencent/MMKV](https://github.com/Tencent/MMKV) for more information * **react-native-mmkv** is a library that allows you to easily use **MMKV** inside your React Native app through fast and direct JS bindings to the native C++ library. ## Features * **Get** and **set** strings, booleans, numbers and ArrayBuffers * **Fully synchronous** calls, no async/await, no Promises, no Bridge. * **Encryption** support (secure storage) * **Multiple instances** support (separate user-data with global data) * **Customizable storage location** * **High performance** because everything is **written in C++** * **~30x faster than AsyncStorage** * Uses [**JSI**](https://reactnative.dev/docs/the-new-architecture/landing-page#fast-javascriptnative-interfacing) and [**C++ TurboModules**](https://github.com/reactwg/react-native-new-architecture/blob/main/docs/turbo-modules-xplat.md) instead of the "old" Bridge * **iOS**, **Android** and **Web** support * Easy to use **React Hooks** API > [!IMPORTANT] > - **You're looking at MMKV V3. If you want to upgrade to the beta, check out the [V4 docs here](./README.md)**! > react-native-mmkv V3 is now a pure C++ TurboModule, and **requires the new architecture to be enabled**. (react-native 0.75+) > - If you want to use react-native-mmkv 3.x.x, you need to enable the new architecture in your app (see ["Enable the New Architecture for Apps"](https://github.com/reactwg/react-native-new-architecture/blob/main/docs/enable-apps.md)) > - For React-Native 0.74.x, use react-native-mmkv 3.0.1. For React-Native 0.75.x and higher, use react-native-mmkv 3.0.2 or higher. > - If you cannot use the new architecture yet, downgrade to react-native-mmkv 2.x.x for now. ## Benchmark [StorageBenchmark](https://github.com/mrousavy/StorageBenchmark) compares popular storage libraries against each other by reading a value from storage for 1000 times:

MMKV vs other storage libraries: Reading a value from Storage 1000 times.
Measured in milliseconds on an iPhone 11 Pro, lower is better.

## Installation ### React Native ```sh yarn add react-native-mmkv cd ios && pod install ``` ### Expo ```sh npx expo install react-native-mmkv npx expo prebuild ``` ## Usage ### Create a new instance To create a new instance of the MMKV storage, use the `MMKV` constructor. It is recommended that you re-use this instance throughout your entire app instead of creating a new instance each time, so `export` the `storage` object. #### Default ```js import { MMKV } from 'react-native-mmkv' export const storage = new MMKV() ``` This creates a new storage instance using the default MMKV storage ID (`mmkv.default`). #### App Groups or Extensions If you want to share MMKV data between your app and other apps or app extensions in the same group, open `Info.plist` and create an `AppGroup` key with your app group's value. MMKV will then automatically store data inside the app group which can be read and written to from other apps or app extensions in the same group by making use of MMKV's multi processing mode. See [Configuring App Groups](https://developer.apple.com/documentation/xcode/configuring-app-groups). #### Customize ```js import { MMKV, Mode } from 'react-native-mmkv' export const storage = new MMKV({ id: `user-${userId}-storage`, path: `${USER_DIRECTORY}/storage`, encryptionKey: 'hunter2', mode: Mode.MULTI_PROCESS, readOnly: false }) ``` This creates a new storage instance using a custom MMKV storage ID. By using a custom storage ID, your storage is separated from the default MMKV storage of your app. The following values can be configured: * `id`: The MMKV instance's ID. If you want to use multiple instances, use different IDs. For example, you can separate the global app's storage and a logged-in user's storage. (required if `path` or `encryptionKey` fields are specified, otherwise defaults to: `'mmkv.default'`) * `path`: The MMKV instance's root path. By default, MMKV stores file inside `$(Documents)/mmkv/`. You can customize MMKV's root directory on MMKV initialization (documentation: [iOS](https://github.com/Tencent/MMKV/wiki/iOS_advance#customize-location) / [Android](https://github.com/Tencent/MMKV/wiki/android_advance#customize-location)) * `encryptionKey`: The MMKV instance's encryption/decryption key. By default, MMKV stores all key-values in plain text on file, relying on iOS's/Android's sandbox to make sure the file is encrypted. Should you worry about information leaking, you can choose to encrypt MMKV. (documentation: [iOS](https://github.com/Tencent/MMKV/wiki/iOS_advance#encryption) / [Android](https://github.com/Tencent/MMKV/wiki/android_advance#encryption)) * `mode`: The MMKV's process behaviour - when set to `MULTI_PROCESS`, the MMKV instance will assume data can be changed from the outside (e.g. App Clips, Extensions or App Groups). * `readOnly`: Whether this MMKV instance should be in read-only mode. This is typically more efficient and avoids unwanted writes to the data if not needed. Any call to `set(..)` will throw. ### Set ```js storage.set('user.name', 'Marc') storage.set('user.age', 21) storage.set('is-mmkv-fast-asf', true) ``` ### Get ```js const username = storage.getString('user.name') // 'Marc' const age = storage.getNumber('user.age') // 21 const isMmkvFastAsf = storage.getBoolean('is-mmkv-fast-asf') // true ``` ### Hooks ```js const [username, setUsername] = useMMKVString('user.name') const [age, setAge] = useMMKVNumber('user.age') const [isMmkvFastAsf, setIsMmkvFastAf] = useMMKVBoolean('is-mmkv-fast-asf') ``` ### Keys ```js // checking if a specific key exists const hasUsername = storage.contains('user.name') // getting all keys const keys = storage.getAllKeys() // ['user.name', 'user.age', 'is-mmkv-fast-asf'] // delete a specific key + value storage.delete('user.name') // delete all keys storage.clearAll() ``` ### Objects ```js const user = { username: 'Marc', age: 21 } // Serialize the object into a JSON string storage.set('user', JSON.stringify(user)) // Deserialize the JSON string into an object const jsonUser = storage.getString('user') // { 'username': 'Marc', 'age': 21 } const userObject = JSON.parse(jsonUser) ``` ### Encryption ```js // encrypt all data with a private key storage.recrypt('hunter2') // remove encryption storage.recrypt(undefined) ``` ### Buffers ```js const buffer = new ArrayBuffer(3) const dataWriter = new Uint8Array(buffer) dataWriter[0] = 1 dataWriter[1] = 100 dataWriter[2] = 255 storage.set('someToken', buffer) const buffer = storage.getBuffer('someToken') console.log(buffer) // [1, 100, 255] ``` ### Size ```js // get size of MMKV storage in bytes const size = storage.size if (size >= 4096) { // clean unused keys and clear memory cache storage.trim() } ``` ## Testing with Jest or Vitest A mocked MMKV instance is automatically used when testing with Jest or Vitest, so you will be able to use `new MMKV()` as per normal in your tests. Refer to [package/example/test/MMKV.test.ts](package/example/test/MMKV.test.ts) for an example using Jest. ## Documentation * [Hooks](https://github.com/mrousavy/react-native-mmkv/blob/v3/docs/HOOKS.md) * [Value-change Listeners](https://github.com/mrousavy/react-native-mmkv/blob/v3/docs/LISTENERS.md) * [Migrate from AsyncStorage](https://github.com/mrousavy/react-native-mmkv/blob/v3/docs/MIGRATE_FROM_ASYNC_STORAGE.md) * [Using MMKV with redux-persist](https://github.com/mrousavy/react-native-mmkv/blob/v3/docs/WRAPPER_REDUX.md) * [Using MMKV with recoil](https://github.com/mrousavy/react-native-mmkv/blob/v3/docs/WRAPPER_RECOIL.md) * [Using MMKV with mobx-persist-storage](https://github.com/mrousavy/react-native-mmkv/blob/v3/docs/WRAPPER_MOBX.md) * [Using MMKV with mobx-persist](https://github.com/mrousavy/react-native-mmkv/blob/v3/docs/WRAPPER_MOBXPERSIST.md) * [Using MMKV with zustand persist-middleware](https://github.com/mrousavy/react-native-mmkv/blob/v3/docs/WRAPPER_ZUSTAND_PERSIST_MIDDLEWARE.md) * [Using MMKV with jotai](https://github.com/mrousavy/react-native-mmkv/blob/v3/docs/WRAPPER_JOTAI.md) * [Using MMKV with react-query](https://github.com/mrousavy/react-native-mmkv/blob/v3/docs/WRAPPER_REACT_QUERY.md) * [Using MMKV with Tinybase](https://github.com/mrousavy/react-native-mmkv/blob/v3/docs/WRAPPER_TINYBASE.md) * [How is this library different from **react-native-mmkv-storage**?](https://github.com/mrousavy/react-native-mmkv/issues/100#issuecomment-886477361) ## LocalStorage and In-Memory Storage (Web) If a user chooses to disable LocalStorage in their browser, the library will automatically provide a limited in-memory storage as an alternative. However, this in-memory storage won't persist data, and users may experience data loss if they refresh the page or close their browser. To optimize user experience, consider implementing a suitable solution within your app to address this scenario. ## Limitations - react-native-mmkv V3 requires react-native 0.74 or higher. - react-native-mmkv V3 requires [the new architecture](https://reactnative.dev/docs/the-new-architecture/landing-page)/TurboModules to be enabled. - Since react-native-mmkv uses JSI for synchronous native method invocations, remote debugging (e.g. with Chrome) is no longer possible. Instead, you should use [Flipper](https://fbflipper.com) or [React DevTools](https://react.dev/learn/react-developer-tools). ## Integrations ### Flipper Use [flipper-plugin-react-native-mmkv](https://github.com/muchobien/flipper-plugin-react-native-mmkv) to debug your MMKV storage using Flipper. You can also simply `console.log` an MMKV instance. ### Reactotron Use [reactotron-react-native-mmkv](https://www.npmjs.com/package/reactotron-react-native-mmkv) to automatically log writes to your MMKV storage using Reactotron. [See the docs for how to setup this plugin with Reactotron.](https://www.npmjs.com/package/reactotron-react-native-mmkv) ## Community Discord [**Join the Margelo Community Discord**](https://margelo.com/discord) to chat about react-native-mmkv or other Margelo libraries. ## Adopting at scale react-native-mmkv is provided _as is_, I work on it in my free time. If you're integrating react-native-mmkv in a production app, consider [funding this project](https://github.com/sponsors/mrousavy) and contact me to receive premium enterprise support, help with issues, prioritize bugfixes, request features, help at integrating react-native-mmkv, and more. ## Contributing See the [contributing guide](CONTRIBUTING.md) to learn how to contribute to the repository and the development workflow. ## License MIT ================================================ FILE: babel.config.js ================================================ module.exports = { presets: ['module:@react-native/babel-preset'], env: { test: { presets: [ ['@babel/preset-env', { targets: { node: 'current' } }], ['@babel/preset-react', { runtime: 'automatic' }], '@babel/preset-typescript' ] } } } ================================================ FILE: bunfig.toml ================================================ [test] # Configure bun test to only run tests in specific directories # This prevents bun test from interfering with Jest tests root = "packages/react-native-mmkv/__bun_tests__" [install] # Opt out from isolated installs linker = "hoisted" ================================================ FILE: docs/HOOKS.md ================================================ # Hooks react-native-mmkv provides an easy to use React-Hooks API to be used in Function Components. ## Reactively use individual keys ```tsx function App() { const [username, setUsername] = useMMKVString("user.name") const [age, setAge] = useMMKVNumber("user.age") const [isPremiumUser, setIsPremiumUser] = useMMKVBoolean("user.isPremium") const [privateKey, setPrivateKey] = useMMKVBuffer("user.privateKey") } ``` ## Clear a key ```tsx function App() { const [username, setUsername] = useMMKVString("user.name") // ... const onLogout = useCallback(() => { setUsername(undefined) }, []) } ``` ## Objects ```tsx type User = { id: string username: string age: number } function App() { const [user, setUser] = useMMKVObject("user") } ``` ## Reactively use an MMKV Instance ```tsx function App() { const storage = useMMKV() // ... const onLogin = useCallback((username) => { storage.set("user.name", "Marc") }, [storage]) } ``` ## Reactively use individual keys from custom instances ```tsx function App() { const globalStorage = useMMKV() const userStorage = useMMKV({ id: `${userId}.storage` }) const [username, setUsername] = useMMKVString("user.name", userStorage) } ``` ## Listen to value changes ```tsx function App() { useMMKVListener((key) => { console.log(`Value for "${key}" changed!`) }) } ``` ## Listen to value changes on a specific instance ```tsx function App() { const storage = useMMKV({ id: `${userId}.storage` }) useMMKVListener((key) => { console.log(`Value for "${key}" changed in user storage!`) }, storage) } ``` ## Listen to all keys in an instance ```tsx function App() { const storage = useMMKV() const keys = useMMKVKeys(storage) } ``` ================================================ FILE: docs/LISTENERS.md ================================================ # Listeners MMKV instances also contain an observer/listener registry. ### Add a listener when a `key`'s `value` changes. ```ts const storage = createMMKV() const listener = storage.addOnValueChangedListener((changedKey) => { const newValue = storage.getString(changedKey) console.log(`"${changedKey}" new value: ${newValue}`) }) ``` Don't forget to remove the listener when no longer needed. For example, when the user logs out: ```ts function SettingsScreen() { // ... const onLogout = useCallback(() => { // ... listener.remove() }, []) // ... } ``` ================================================ FILE: docs/MIGRATE_FROM_ASYNC_STORAGE.md ================================================ # Migrate from AsyncStorage Here's a migration script to copy all values from AsyncStorage to MMKV, and delete them from AsyncStorage afterwards.
storage.ts
```ts import AsyncStorage from '@react-native-async-storage/async-storage'; import { createMMKV } from 'react-native-mmkv'; export const storage = createMMKV(); // TODO: Remove `hasMigratedFromAsyncStorage` after a while (when everyone has migrated) export const hasMigratedFromAsyncStorage = storage.getBoolean( 'hasMigratedFromAsyncStorage', ); // TODO: Remove `hasMigratedFromAsyncStorage` after a while (when everyone has migrated) export async function migrateFromAsyncStorage(): Promise { console.log('Migrating from AsyncStorage -> MMKV...'); const start = global.performance.now(); const keys = await AsyncStorage.getAllKeys(); for (const key of keys) { try { const value = await AsyncStorage.getItem(key); if (value != null) { if (['true', 'false'].includes(value)) { storage.set(key, value === 'true'); } else { storage.set(key, value); } AsyncStorage.removeItem(key); } } catch (error) { console.error( `Failed to migrate key "${key}" from AsyncStorage to MMKV!`, error, ); throw error; } } storage.set('hasMigratedFromAsyncStorage', true); const end = global.performance.now(); console.log(`Migrated from AsyncStorage -> MMKV in ${end - start}ms!`); } ```
App.tsx
```tsx ... import { hasMigratedFromAsyncStorage, migrateFromAsyncStorage } from './storage'; ... export default function App() { // TODO: Remove `hasMigratedFromAsyncStorage` after a while (when everyone has migrated) const [hasMigrated, setHasMigrated] = useState(hasMigratedFromAsyncStorage); ... useEffect(() => { if (!hasMigratedFromAsyncStorage) { InteractionManager.runAfterInteractions(async () => { try { await migrateFromAsyncStorage() setHasMigrated(true) } catch (e) { // TODO: fall back to AsyncStorage? Wipe storage clean and use MMKV? Crash app? } }); } }, []); if (!hasMigrated) { // show loading indicator while app is migrating storage... return ( ); } return ( ); } ```
================================================ FILE: docs/V4_UPGRADE_GUIDE.md ================================================ # V4 Upgrade Guide react-native-mmkv v4 has been fully rewritten to [nitro](https://nitro.margelo.com), which greatly simplifies the codebase, optimized native calls, and optimized the implementation. Ideally, this means; - **Backwards compatible for old architecture** again thanks to Nitro 🥳 - Easier to maintain, allows for PRs from people without JSI experience 🫂 - Lightweight & fast native calls thanks to Nitro 🔥 Also, the core MMKV library is now consumed from the official distribution channels - that is **CocoaPods** on iOS, and **Gradle Prefabs** on Android. This means you can use MMKV Core from _your native code_ again by just adding it to your `Podfile`/`build.gradle` dependencies! ## Breaking changes There have been a few breaking changes. This guide will help you migrate over from V3 to V4: ### Nitro Modules dependency Since react-native-mmkv is now a Nitro Module, you need to install the [react-native-nitro-modules](https://github.com/mrousavy/nitro) core dependency in your app: ```sh npm install react-native-nitro-modules ``` > Nitro requires **react-native 0.75.0** or higher. See [the Troubleshooting guide](https://nitro.margelo.com/docs/troubleshooting) if you run into any issues. ### `new MMKV(...)` -> `createMMKV(...)` The `MMKV` JS-class no longer exists - instead it is now purely native. This means, you have to change your MMKV creation code: ```diff - const storage = new MMKV() + const storage = createMMKV() ``` ### `.delete(...)` -> `.remove(...)` The `MMKV.delete(...)` function has been renamed to `MMKV.remove(...)`, since `delete` is a reserved keyword in C++: ```diff - storage.delete('my-key') + storage.remove('my-key') ``` ### `AppGroup` -> `AppGroupIdentifier` To better comply with Apple's naming, I changed the `AppGroup` key to `AppGroupIdentifier`. If you used MMKV with App Groups, make sure you change the key in your `Info.plist`: ```diff - AppGroup + AppGroupIdentifier ``` ## Troubleshooting ### iOS build failed: `The following Swift pods cannot yet be integrated as static libraries` If you get an iOS `pod install` error that looks like this: ``` ⚠️ Something went wrong running `pod install` in the `ios` directory. Command `pod install` failed. └─ Cause: The following Swift pods cannot yet be integrated as static libraries: The Swift pod `NitroMmkv` depends upon `MMKVCore`, which does not define modules. To opt into those targets generating module maps (which is necessary to import them from Swift when building as static libraries), you may set `use_modular_headers!` globally in your Podfile, or specify `:modular_headers => true` for particular dependencies. ``` ..you are likely on an old version of `MMKVCore`. Make sure to update to a version that includes [this PR](https://github.com/Tencent/MMKV/pull/1579) (v2.2.4 or higher), or add this to your `Podfile`: ```rb pod 'MMKVCore', :modular_headers => true ``` If you are on the latest react-native-mmkv V4 version, it should include a working `MMKVCore` by default - so you shouldn't see this error unless you manually added a dependency on `MMKVCore`/`MMKV` to your `Podfile`. ================================================ FILE: docs/WRAPPER_JOTAI.md ================================================ # jotai wrapper If you want to use MMKV with [Jotai](https://github.com/pmndrs/jotai), create the following `atomWithMMKV` function: ```ts import { atomWithStorage, createJSONStorage } from 'jotai/utils'; import { createMMKV } from 'react-native-mmkv'; const storage = createMMKV(); function getItem(key: string): string | null { const value = storage.getString(key) return value ? value : null } function setItem(key: string, value: string): void { storage.set(key, value) } function removeItem(key: string): void { storage.remove(key); } function subscribe( key: string, callback: (value: string | null) => void ): () => void { const listener = (changedKey: string) => { if (changedKey === key) { callback(getItem(key)) } } const { remove } = storage.addOnValueChangedListener(listener) return () => { remove() } } export const atomWithMMKV = (key: string, initialValue: T) => atomWithStorage( key, initialValue, createJSONStorage(() => ({ getItem, setItem, removeItem, subscribe, })), { getOnInit: true } ); ``` Then simply use `atomWithMMKV(..)` instead of `atom(..)` when creating an atom you'd like to persist accross app starts. ```ts const myAtom = atomWithMMKV('my-atom-key', 'value'); ``` *Note:* `createJSONStorage` handles `JSON.stringify()`/`JSON.parse()` when setting and returning the stored value. See the official Jotai doc here: https://jotai.org/docs/utils/atom-with-storage ================================================ FILE: docs/WRAPPER_MOBX.md ================================================ # mobx-persist-store wrapper If you want to use MMKV with [mobx-persist-store](https://github.com/quarrant/mobx-persist-store), create the following `storage` object: ```ts import { configurePersistable } from 'mobx-persist-store' import { createMMKV } from "react-native-mmkv" const storage = createMMKV() configurePersistable({ storage: { setItem: (key, data) => storage.set(key, data), getItem: (key) => storage.getString(key), removeItem: (key) => storage.remove(key), }, }) ``` ================================================ FILE: docs/WRAPPER_MOBXPERSIST.md ================================================ # mobx-persist wrapper If you want to use MMKV with [mobx-persist](https://github.com/pinqy520/mobx-persist), create the following `hydrate` function: ```ts import { create } from "mobx-persist" import { createMMKV } from "react-native-mmkv" const storage = createMMKV() const mmkvStorage = { clear: () => { storage.clearAll() return Promise.resolve() }, setItem: (key, value) => { storage.set(key, value) return Promise.resolve(true) }, getItem: (key) => { const value = storage.getString(key) return Promise.resolve(value) }, removeItem: (key) => { storage.remove(key) return Promise.resolve() }, } const hydrate = create({ storage: mmkvStorage, jsonify: true, }) ``` You can see a full working example [here](https://github.com/riamon-v/rn-mmkv-with-mobxpersist) ================================================ FILE: docs/WRAPPER_REACT_QUERY.md ================================================ # react-query wrapper If you want to use MMKV with [react-query](https://tanstack.com/query/latest/docs/framework/react/overview), follow further steps: 1. Install `react-query` persist packages ```sh yarn add @tanstack/query-async-storage-persister @tanstack/react-query-persist-client ``` 2. Add next code into your app ```ts import { createAsyncStoragePersister } from '@tanstack/query-async-storage-persister' import { createMMKV } from "react-native-mmkv" const storage = createMMKV(); const clientStorage = { setItem: (key, value) => { storage.set(key, value); }, getItem: (key) => { const value = storage.getString(key); return value === undefined ? null : value; }, removeItem: (key) => { storage.remove(key); }, }; export const clientPersister = createAsyncStoragePersister({ storage: clientStorage }); ``` 3. Use created `clientPersister` in your root component (eg. `App.tsx`) ```tsx import { PersistQueryClientProvider } from '@tanstack/react-query-persist-client' const App = () => { return ( {...} ); }; ``` For more information check their official [docs](https://tanstack.com/query/latest/docs/framework/react/plugins/createAsyncStoragePersister) ================================================ FILE: docs/WRAPPER_RECOIL.md ================================================ # recoil storage wrapper If you want to use MMKV with [recoil](https://recoiljs.org/), Use the following persist code: ```tsx const persistAtom = (key) => ({ setSelf, onSet }) => { setSelf(() => { let data = storage.getString(key); if (data != null){ return JSON.parse(data); } else { return new DefaultValue(); } }); onSet((newValue, _, isReset) => { if (isReset) { storage.remove(key); } else { storage.set(key, JSON.stringify(newValue)); } }); }; ``` ================================================ FILE: docs/WRAPPER_REDUX.md ================================================ # redux-persist storage wrapper If you want to use MMKV with [redux-persist](https://github.com/rt2zz/redux-persist), create the following `storage` object: ```ts import { Storage } from 'redux-persist' import { createMMKV } from "react-native-mmkv" const storage = createMMKV() export const reduxStorage: Storage = { setItem: (key, value) => { storage.set(key, value) return Promise.resolve(true) }, getItem: (key) => { const value = storage.getString(key) return Promise.resolve(value) }, removeItem: (key) => { storage.remove(key) return Promise.resolve() }, } ``` ================================================ FILE: docs/WRAPPER_TINYBASE.md ================================================ # tinybase wrapper If you want to use MMKV with [Tinybase](https://tinybase.org/api/persister-react-native-mmkv), follow these steps: ```ts import { createMMKV } from 'react-native-mmkv' import { createStore } from 'tinybase'; import { createReactNativeMmkvPersister } from 'tinybase/persisters/persister-react-native-mmkv'; const storage = createMMKV() const store = createStore().setTables({ pets: { fido: { species: 'dog' } } }); const persister = createReactNativeMmkvPersister(store, storage); await persister.save(); ``` Similarly, to set up with the react hook: ```tsx const storage = createMMKV() const App = () => { useCreatePersister( store, store => createReactNativeMmkvPersister(store, storage), [], async persister => { // ... }, ); } ``` For more information check their official [docs](https://tinybase.org/api/persister-react-native-mmkv/functions/creation/createreactnativemmkvpersister/) ================================================ FILE: docs/WRAPPER_ZUSTAND_PERSIST_MIDDLEWARE.md ================================================ # zustand persist-middleware wrapper If you want to use MMKV with [zustand persist-middleware](https://github.com/pmndrs/zustand#persist-middleware), create the following `storage` object: ```ts import { StateStorage } from 'zustand/middleware' import { createMMKV } from 'react-native-mmkv' const storage = createMMKV() const zustandStorage: StateStorage = { setItem: (name, value) => { return storage.set(name, value) }, getItem: (name) => { const value = storage.getString(name) return value ?? null }, removeItem: (name) => { return storage.remove(name) }, } ``` ================================================ FILE: example/.eslintrc.js ================================================ module.exports = { root: true, extends: '@react-native', }; ================================================ FILE: example/.gitignore ================================================ # OSX # .DS_Store # Xcode # build/ *.pbxuser !default.pbxuser *.mode1v3 !default.mode1v3 *.mode2v3 !default.mode2v3 *.perspectivev3 !default.perspectivev3 xcuserdata *.xccheckout *.moved-aside DerivedData *.hmap *.ipa *.xcuserstate **/.xcode.env.local # Android/IntelliJ # build/ .idea .gradle local.properties *.iml *.hprof .cxx/ *.keystore !debug.keystore .kotlin/ # node.js # node_modules/ npm-debug.log yarn-error.log # fastlane # # It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the # screenshots whenever they are needed. # For more information about the recommended setup visit: # https://docs.fastlane.tools/best-practices/source-control/ **/fastlane/report.xml **/fastlane/Preview.html **/fastlane/screenshots **/fastlane/test_output # Bundle artifact *.jsbundle # Ruby / CocoaPods **/Pods/ /vendor/bundle/ # Temporary files created by Metro to check the health of the file watcher .metro-health-check* # testing /coverage # Yarn .yarn/* !.yarn/patches !.yarn/plugins !.yarn/releases !.yarn/sdks !.yarn/versions ================================================ FILE: example/.prettierrc.js ================================================ module.exports = { arrowParens: 'avoid', singleQuote: true, trailingComma: 'all', }; ================================================ FILE: example/.watchmanconfig ================================================ {} ================================================ FILE: example/Gemfile ================================================ source 'https://rubygems.org' # You may use http://rbenv.org/ or https://rvm.io/ to install and use this version ruby ">= 2.6.10" # Exclude problematic versions of cocoapods and activesupport that causes build failures. gem 'cocoapods', '>= 1.13', '!= 1.15.1', '!= 1.15.0' gem 'activesupport', '>= 6.1.7.5', '!= 7.1.0' gem 'xcodeproj', '< 1.26.0' gem 'concurrent-ruby', '< 1.3.4' # Ruby 3.4.0 has removed some libraries from the standard library. gem 'bigdecimal' gem 'logger' gem 'benchmark' gem 'mutex_m' ================================================ FILE: example/README.md ================================================ This is a new [**React Native**](https://reactnative.dev) project, bootstrapped using [`@react-native-community/cli`](https://github.com/react-native-community/cli). # Getting Started > **Note**: Make sure you have completed the [Set Up Your Environment](https://reactnative.dev/docs/set-up-your-environment) guide before proceeding. ## Step 1: Start Metro First, you will need to run **Metro**, the JavaScript build tool for React Native. To start the Metro dev server, run the following command from the root of your React Native project: ```sh # Using npm npm start # OR using Yarn yarn start ``` ## Step 2: Build and run your app With Metro running, open a new terminal window/pane from the root of your React Native project, and use one of the following commands to build and run your Android or iOS app: ### Android ```sh # Using npm npm run android # OR using Yarn yarn android ``` ### iOS For iOS, remember to install CocoaPods dependencies (this only needs to be run on first clone or after updating native deps). The first time you create a new project, run the Ruby bundler to install CocoaPods itself: ```sh bundle install ``` Then, and every time you update your native dependencies, run: ```sh bundle exec pod install ``` For more information, please visit [CocoaPods Getting Started guide](https://guides.cocoapods.org/using/getting-started.html). ```sh # Using npm npm run ios # OR using Yarn yarn ios ``` If everything is set up correctly, you should see your new app running in the Android Emulator, iOS Simulator, or your connected device. This is one way to run your app — you can also build it directly from Android Studio or Xcode. ## Step 3: Modify your app Now that you have successfully run the app, let's make changes! Open `App.tsx` in your text editor of choice and make some changes. When you save, your app will automatically update and reflect these changes — this is powered by [Fast Refresh](https://reactnative.dev/docs/fast-refresh). When you want to forcefully reload, for example to reset the state of your app, you can perform a full reload: - **Android**: Press the R key twice or select **"Reload"** from the **Dev Menu**, accessed via Ctrl + M (Windows/Linux) or Cmd ⌘ + M (macOS). - **iOS**: Press R in iOS Simulator. ## Congratulations! :tada: You've successfully run and modified your React Native App. :partying_face: ### Now what? - If you want to add this new React Native code to an existing application, check out the [Integration guide](https://reactnative.dev/docs/integration-with-existing-apps). - If you're curious to learn more about React Native, check out the [docs](https://reactnative.dev/docs/getting-started). # Troubleshooting If you're having issues getting the above steps to work, see the [Troubleshooting](https://reactnative.dev/docs/troubleshooting) page. # Learn More To learn more about React Native, take a look at the following resources: - [React Native Website](https://reactnative.dev) - learn more about React Native. - [Getting Started](https://reactnative.dev/docs/environment-setup) - an **overview** of React Native and how setup your environment. - [Learn the Basics](https://reactnative.dev/docs/getting-started) - a **guided tour** of the React Native **basics**. - [Blog](https://reactnative.dev/blog) - read the latest official React Native **Blog** posts. - [`@facebook/react-native`](https://github.com/facebook/react-native) - the Open Source; GitHub **repository** for React Native. ================================================ FILE: example/__tests__/MMKV.harness.ts ================================================ import { describe, it, expect, beforeEach, afterEach, } from 'react-native-harness'; import { MMKV, createMMKV, deleteMMKV, existsMMKV } from 'react-native-mmkv'; const waitForNextTick = async () => { await new Promise(resolve => setTimeout(resolve, 0)); }; describe('MMKV Core Functionality', () => { let storage: MMKV; beforeEach(() => { storage = createMMKV(); storage.clearAll(); // Start with clean state }); afterEach(() => { storage.clearAll(); // Clean up after each test }); describe('Basic CRUD Operations', () => { it('should store and retrieve string values correctly', () => { const testKey = 'testString'; const testValue = 'Hello MMKV!'; storage.set(testKey, testValue); expect(storage.getString(testKey)).toStrictEqual(testValue); expect(storage.contains(testKey)).toBe(true); expect(storage.getAllKeys()).toContain(testKey); }); it('should store and retrieve number values correctly', () => { const testKey = 'testNumber'; const testValue = 42.5; storage.set(testKey, testValue); expect(storage.getNumber(testKey)).toStrictEqual(testValue); expect(storage.contains(testKey)).toBe(true); }); it('should store and retrieve boolean values correctly', () => { const testKey = 'testBoolean'; storage.set(testKey, true); expect(storage.getBoolean(testKey)).toStrictEqual(true); storage.set(testKey, false); expect(storage.getBoolean(testKey)).toStrictEqual(false); }); it('should store and retrieve values with correct types', () => { storage.set('stringKey', 'value'); storage.set('numberKey', 123); storage.set('booleanKey', true); // Correct type access should work expect(storage.getString('stringKey')).toStrictEqual('value'); expect(storage.getNumber('numberKey')).toStrictEqual(123); expect(storage.getBoolean('booleanKey')).toStrictEqual(true); }); it('should handle type interpretation from raw bytes', () => { // MMKV stores raw bytes, so reading with wrong type may return interpreted values // rather than undefined, depending on the underlying byte representation storage.set('numberKey', 42); // Reading a number as string/boolean may return some interpreted value // We just verify it doesn't crash and returns something const stringResult = storage.getString('numberKey'); const booleanResult = storage.getBoolean('numberKey'); // These may or may not be undefined depending on byte interpretation expect(typeof stringResult).toBeDefined(); expect(typeof booleanResult).toBeDefined(); // But the correct type should still work expect(storage.getNumber('numberKey')).toStrictEqual(42); }); it('should remove values correctly', () => { const testKey = 'removeTest'; storage.set(testKey, 'value'); expect(storage.contains(testKey)).toBe(true); storage.remove(testKey); expect(storage.contains(testKey)).toBe(false); expect(storage.getString(testKey)).toBeUndefined(); expect(storage.getAllKeys()).not.toContain(testKey); }); it('should clear all values correctly', () => { storage.set('key1', 'value1'); storage.set('key2', 42); storage.set('key3', true); expect(storage.getAllKeys().length).toBeGreaterThan(0); storage.clearAll(); expect(storage.getAllKeys()).toEqual([]); }); it('should return undefined for non-existent keys', () => { const nonExistentKey = 'doesNotExist'; expect(storage.getString(nonExistentKey)).toBeUndefined(); expect(storage.getNumber(nonExistentKey)).toBeUndefined(); expect(storage.getBoolean(nonExistentKey)).toBeUndefined(); expect(storage.getBuffer(nonExistentKey)).toBeUndefined(); expect(storage.contains(nonExistentKey)).toBe(false); }); }); describe('Key Management', () => { it('should handle getAllKeys correctly', () => { const keys = ['key1', 'key2', 'key3']; keys.forEach((key, index) => { storage.set(key, `value${index}`); }); const retrievedKeys = storage.getAllKeys(); keys.forEach(key => { expect(retrievedKeys).toContain(key); }); }); it('should handle special characters in keys', () => { const specialKeys = [ 'key with spaces', 'key-with-dashes', 'key_with_underscores', 'key.with.dots', 'key/with/slashes', 'émoji-key-🚀', ]; specialKeys.forEach(key => { storage.set(key, 'test value'); expect(storage.getString(key)).toStrictEqual('test value'); expect(storage.contains(key)).toBe(true); }); }); }); describe('Value Overwriting', () => { it('should overwrite existing values', () => { const key = 'overwriteTest'; storage.set(key, 'original'); expect(storage.getString(key)).toStrictEqual('original'); storage.set(key, 'updated'); expect(storage.getString(key)).toStrictEqual('updated'); }); it('should handle type changes for the same key', () => { const key = 'typeChangeTest'; storage.set(key, 'string value'); expect(storage.getString(key)).toStrictEqual('string value'); storage.set(key, 42); expect(storage.getNumber(key)).toStrictEqual(42); storage.set(key, true); expect(storage.getBoolean(key)).toStrictEqual(true); }); }); describe('Edge Cases', () => { it('should handle empty string values', () => { const key = 'emptyString'; storage.set(key, ''); expect(storage.getString(key)).toStrictEqual(''); expect(storage.contains(key)).toBe(true); }); it('should handle zero and negative numbers', () => { storage.set('zero', 0); storage.set('negative', -42.5); expect(storage.getNumber('zero')).toStrictEqual(0); expect(storage.getNumber('negative')).toStrictEqual(-42.5); }); it('should handle very long strings', () => { const longString = 'A'.repeat(10000); const key = 'longString'; storage.set(key, longString); expect(storage.getString(key)).toStrictEqual(longString); }); it('should handle many keys', () => { const keyCount = 1000; const keys: string[] = []; for (let i = 0; i < keyCount; i++) { const key = `key${i}`; keys.push(key); storage.set(key, i); } // Verify all keys exist const allKeys = storage.getAllKeys(); expect(allKeys.length).toBeGreaterThanOrEqual(keyCount); // Verify random samples for (let i = 0; i < 10; i++) { const randomIndex = Math.floor(Math.random() * keyCount); const key = `key${randomIndex}`; expect(storage.getNumber(key)).toStrictEqual(randomIndex); } }); }); describe('ArrayBuffer/Buffer Operations', () => { it('should store and retrieve ArrayBuffer correctly', () => { const key = 'bufferTest'; const data = new Uint8Array([1, 2, 3, 4, 5, 255]); const buffer = data.buffer; storage.set(key, buffer); const retrieved = storage.getBuffer(key); expect(retrieved).toBeDefined(); expect(retrieved!.byteLength).toStrictEqual(buffer.byteLength); const retrievedArray = new Uint8Array(retrieved!); expect(retrievedArray).toEqual(data); }); it('should handle empty ArrayBuffer', () => { const key = 'emptyBuffer'; const emptyBuffer = new ArrayBuffer(0); storage.set(key, emptyBuffer); const retrieved = storage.getBuffer(key); expect(retrieved).toBeDefined(); expect(retrieved!.byteLength).toStrictEqual(0); }); it('should handle large ArrayBuffer', () => { const key = 'largeBuffer'; const size = 1024 * 1024; // 1MB const data = new Uint8Array(size); // Fill with pattern for (let i = 0; i < size; i++) { data[i] = i % 256; } storage.set(key, data.buffer); const retrieved = storage.getBuffer(key); expect(retrieved).toBeDefined(); expect(retrieved!.byteLength).toStrictEqual(size); const retrievedArray = new Uint8Array(retrieved!); // Check pattern at random positions for (let i = 0; i < 100; i++) { const pos = Math.floor(Math.random() * size); expect(retrievedArray[pos]).toStrictEqual(pos % 256); } }); it('should handle different typed arrays', () => { const int16Data = new Int16Array([1000, -1000, 32767, -32768]); const float32Data = new Float32Array([3.14159, -2.718, 1.414]); const uint32Data = new Uint32Array([0, 1, 4294967295]); storage.set('int16', int16Data.buffer); storage.set('float32', float32Data.buffer); storage.set('uint32', uint32Data.buffer); const int16Retrieved = new Int16Array(storage.getBuffer('int16')!); const float32Retrieved = new Float32Array(storage.getBuffer('float32')!); const uint32Retrieved = new Uint32Array(storage.getBuffer('uint32')!); expect(int16Retrieved).toEqual(int16Data); expect(float32Retrieved).toEqual(float32Data); expect(uint32Retrieved).toEqual(uint32Data); }); it('should handle buffer type interpretation', () => { const key = 'bufferTypeTest'; const data = new Uint8Array([65, 66, 67]); // 'ABC' in ASCII storage.set(key, data.buffer); // Buffer should be retrievable as buffer expect(storage.getBuffer(key)).toBeDefined(); // Other types may return interpreted values from the raw bytes // We just verify they don't crash const stringResult = storage.getString(key); const numberResult = storage.getNumber(key); const booleanResult = storage.getBoolean(key); // These may or may not be undefined depending on byte interpretation expect(() => stringResult).not.toThrow(); expect(() => numberResult).not.toThrow(); expect(() => booleanResult).not.toThrow(); }); }); }); describe('MMKV Configuration & Multiple Instances', () => { afterEach(() => { // Clean up all test instances try { createMMKV({ id: 'test-instance-1' }).clearAll(); createMMKV({ id: 'test-instance-2' }).clearAll(); createMMKV({ id: 'encrypted-instance' }).clearAll(); } catch { // Instances might not exist, that's okay } }); describe('Instance Configuration', () => { it('should create instances with different IDs', () => { const storage1 = createMMKV({ id: 'test-instance-1' }); const storage2 = createMMKV({ id: 'test-instance-2' }); // Set values in different instances storage1.set('shared-key', 'value-from-instance-1'); storage2.set('shared-key', 'value-from-instance-2'); // Values should be isolated expect(storage1.getString('shared-key')).toStrictEqual( 'value-from-instance-1', ); expect(storage2.getString('shared-key')).toStrictEqual( 'value-from-instance-2', ); }); it('should handle default instance vs custom instance isolation', () => { const defaultStorage = createMMKV(); const customStorage = createMMKV({ id: 'custom-test' }); const key = 'isolation-test'; defaultStorage.set(key, 'default-value'); customStorage.set(key, 'custom-value'); expect(defaultStorage.getString(key)).toStrictEqual('default-value'); expect(customStorage.getString(key)).toStrictEqual('custom-value'); // Clean up custom instance customStorage.clearAll(); }); it('should reuse same instance for same configuration', () => { const config = { id: 'reuse-test' }; const storage1 = createMMKV(config); const storage2 = createMMKV(config); storage1.set('test-key', 'test-value'); // Both references should point to same instance expect(storage2.getString('test-key')).toStrictEqual('test-value'); // Clean up storage1.clearAll(); }); }); describe('Instance Management', () => { it('should handle multiple instances independently', () => { const instances = Array.from({ length: 5 }, (_, i) => createMMKV({ id: `multi-instance-${i}` }), ); // Set different values in each instance instances.forEach((instance, i) => { instance.set('instance-number', i); instance.set('instance-name', `instance-${i}`); }); // Verify isolation instances.forEach((instance, i) => { expect(instance.getNumber('instance-number')).toStrictEqual(i); expect(instance.getString('instance-name')).toStrictEqual( `instance-${i}`, ); }); // Clean up instances.forEach(instance => instance.clearAll()); }); it('should import other keys properly', () => { const storage1 = createMMKV({ id: 'first-storage' }) const storage2 = createMMKV({ id: 'second-storage' }) storage1.clearAll() storage2.clearAll() expect(storage1.getAllKeys()).toEqual([]) expect(storage2.getAllKeys()).toEqual([]) storage1.set('key1', 'value1') storage1.set('key2', 42) storage1.set('key3', true) expect(storage1.getAllKeys().length).toStrictEqual(3) expect(storage2.getAllKeys().length).toStrictEqual(0) storage2.importAllFrom(storage1) expect(storage1.getAllKeys().length).toStrictEqual(3) expect(storage2.getAllKeys().length).toStrictEqual(3) expect(storage2.getString('key1')).toStrictEqual('value1') expect(storage2.getNumber('key2')).toStrictEqual(42) expect(storage2.getBoolean('key3')).toStrictEqual(true) }) it('should handle instance properties correctly', () => { const storage = createMMKV({ id: 'properties-test' }); // Initially empty expect(storage.getAllKeys()).toEqual([]); // Add some data storage.set('key1', 'value1'); storage.set('key2', 42); expect(typeof storage.length).toBe('number'); expect(storage.length).toStrictEqual(2); expect(storage.getAllKeys().length).toStrictEqual(2); // Clean up storage.clearAll(); }); }); }); describe('MMKV Encryption & Security', () => { afterEach(() => { // Clean up encrypted instances try { createMMKV({ id: 'encrypted-test-128' }).clearAll(); createMMKV({ id: 'recrypt-test-128' }).clearAll(); createMMKV({ id: 'encrypted-test-256' }).clearAll(); createMMKV({ id: 'recrypt-test-256' }).clearAll(); } catch { // Instances might not exist, that's okay } }); describe('Encryption (AES-128)', () => { it('should create encrypted instance and store data', () => { const encryptionKey = 'test-key-123456'; const storage = createMMKV({ id: 'encrypted-test-128', encryptionKey, }); storage.set('secret-data', 'confidential information'); storage.set('secret-number', 42); storage.set('secret-boolean', true); expect(storage.getString('secret-data')).toStrictEqual( 'confidential information', ); expect(storage.getNumber('secret-number')).toStrictEqual(42); expect(storage.getBoolean('secret-boolean')).toStrictEqual(true); }); it('should isolate encrypted and non-encrypted instances', () => { const plainStorage = createMMKV({ id: 'plain-test' }); const encryptedStorage = createMMKV({ id: 'encrypted-isolation-test-128', encryptionKey: 'secret-key-456', }); const key = 'shared-key'; plainStorage.set(key, 'plain-value'); encryptedStorage.set(key, 'encrypted-value'); expect(plainStorage.getString(key)).toStrictEqual('plain-value'); expect(encryptedStorage.getString(key)).toStrictEqual('encrypted-value'); // Clean up plainStorage.clearAll(); encryptedStorage.clearAll(); }); it('should handle recryption', () => { const storage = createMMKV({ id: 'recrypt-test-128' }); expect(storage.isEncrypted).toStrictEqual(false) // Set data without encryption storage.set('data-key', 'original-data'); expect(storage.getString('data-key')).toStrictEqual('original-data'); // Encrypt the storage storage.encrypt('new-encryption-key'); expect(storage.isEncrypted).toStrictEqual(true) expect(storage.getString('data-key')).toStrictEqual('original-data'); // Change encryption key storage.encrypt('different-key-123'); expect(storage.isEncrypted).toStrictEqual(true) expect(storage.getString('data-key')).toStrictEqual('original-data'); // Remove encryption storage.decrypt(); expect(storage.isEncrypted).toStrictEqual(false) expect(storage.getString('data-key')).toStrictEqual('original-data'); }); it('should handle encryption key validation', () => { // Test maximum key length (16 bytes) const maxKey = '1234567890123456'; // exactly 16 characters const storage = createMMKV({ id: 'key-validation-test', encryptionKey: maxKey, }); expect(storage.isEncrypted).toStrictEqual(true) storage.set('test', 'value'); expect(storage.getString('test')).toStrictEqual('value'); storage.clearAll(); }); }); describe('Encryption (AES-256)', () => { it('should create encrypted instance and store data', () => { const encryptionKey = 'test-key-123456-longer-than-16'; const storage = createMMKV({ id: 'encrypted-test-256', encryptionKey, encryptionType: 'AES-256', }); storage.set('secret-data', 'confidential information'); storage.set('secret-number', 42); storage.set('secret-boolean', true); expect(storage.getString('secret-data')).toStrictEqual( 'confidential information', ); expect(storage.getNumber('secret-number')).toStrictEqual(42); expect(storage.getBoolean('secret-boolean')).toStrictEqual(true); }); it('should isolate encrypted and non-encrypted instances', () => { const plainStorage = createMMKV({ id: 'plain-test' }); const encryptedStorage = createMMKV({ id: 'encrypted-isolation-test-256', encryptionKey: 'secret-key-456', encryptionType: 'AES-256', }); const key = 'shared-key'; plainStorage.set(key, 'plain-value'); encryptedStorage.set(key, 'encrypted-value'); expect(plainStorage.getString(key)).toStrictEqual('plain-value'); expect(encryptedStorage.getString(key)).toStrictEqual('encrypted-value'); // Clean up plainStorage.clearAll(); encryptedStorage.clearAll(); }); it('should handle recryption', () => { // TODO: Add encryptionType to recrypt const storage = createMMKV({ id: 'recrypt-test-256' }); expect(storage.isEncrypted).toStrictEqual(false) // Set data without encryption storage.set('data-key', 'original-data'); expect(storage.getString('data-key')).toStrictEqual('original-data'); // Encrypt the storage storage.encrypt('new-encryption-key', 'AES-256'); expect(storage.isEncrypted).toStrictEqual(true) expect(storage.getString('data-key')).toStrictEqual('original-data'); // Change encryption key storage.encrypt('different-key-123', 'AES-256'); expect(storage.isEncrypted).toStrictEqual(true) expect(storage.getString('data-key')).toStrictEqual('original-data'); // Remove encryption storage.decrypt() expect(storage.isEncrypted).toStrictEqual(false) expect(storage.getString('data-key')).toStrictEqual('original-data'); }); it('should handle encryption key validation', () => { // Test maximum key length (32 bytes) const maxKey = '12345678901234561234567890123456'; // exactly 32 characters const storage = createMMKV({ id: 'key-validation-test', encryptionKey: maxKey, encryptionType: 'AES-256', }); storage.set('test', 'value'); expect(storage.getString('test')).toStrictEqual('value'); storage.clearAll(); }); }); }); describe('MMKV Read-Only Mode', () => { // Note: MMKV caches instances by ID, so once an ID is opened with a given // mode it cannot be reopened with a different mode in the same process. // These tests use an ID that is only ever opened as read-only. it('should report isReadOnly as true', () => { const storage = createMMKV({ id: 'read-only-fresh-test', readOnly: true }); expect(storage.isReadOnly).toStrictEqual(true); }); it('should report isReadOnly as false for writable instance', () => { const storage = createMMKV({ id: 'writable-mode-test' }); expect(storage.isReadOnly).toStrictEqual(false); storage.clearAll(); }); it('should throw when trying to set a value', () => { const storage = createMMKV({ id: 'read-only-set-test', readOnly: true }); expect(() => storage.set('key', 'value')).toThrow(); }); it('should not remove values in read-only mode', () => { const storage = createMMKV({ id: 'read-only-remove-test', readOnly: true }); // MMKV silently no-ops remove on read-only instances expect(storage.remove('key')).toStrictEqual(false); }); it('should not clear values in read-only mode', () => { const storage = createMMKV({ id: 'read-only-clear-test', readOnly: true }); // MMKV silently no-ops clearAll on read-only instances storage.clearAll(); expect(storage.length).toStrictEqual(0); }); it('should support contains and getAllKeys on empty read-only instance', () => { const storage = createMMKV({ id: 'read-only-keys-test', readOnly: true }); expect(storage.contains('nonexistent')).toBe(false); expect(storage.getAllKeys()).toEqual([]); expect(storage.length).toStrictEqual(0); }); }); describe('MMKV Compare Before Set', () => { afterEach(() => { try { createMMKV({ id: 'compare-before-set-test' }).clearAll(); createMMKV({ id: 'compare-disabled-test' }).clearAll(); } catch { // Instances might not exist, that's okay } }); it('should create instance with compareBeforeSet enabled', () => { const storage = createMMKV({ id: 'compare-before-set-test', compareBeforeSet: true, }); storage.set('key', 'value'); expect(storage.getString('key')).toStrictEqual('value'); storage.set('key', 'updated'); expect(storage.getString('key')).toStrictEqual('updated'); }); it('should create instance with compareBeforeSet disabled', () => { const storage = createMMKV({ id: 'compare-disabled-test', compareBeforeSet: false, }); storage.set('key', 'value'); expect(storage.getString('key')).toStrictEqual('value'); storage.set('key', 'updated'); expect(storage.getString('key')).toStrictEqual('updated'); }); it('should not change byteSize when setting same value with compareBeforeSet', () => { const storage = createMMKV({ id: 'compare-before-set-test', compareBeforeSet: true, }); storage.set('str', 'hello'); storage.set('num', 42); storage.set('bool', true); storage.set('buf', new Uint8Array([1, 2, 3]).buffer); const sizeAfterInitialSet = storage.byteSize; // Set same values again storage.set('str', 'hello'); storage.set('num', 42); storage.set('bool', true); storage.set('buf', new Uint8Array([1, 2, 3]).buffer); // byteSize should not have changed expect(storage.byteSize).toStrictEqual(sizeAfterInitialSet); }); it('should change byteSize when setting a different value with compareBeforeSet', () => { const storage = createMMKV({ id: 'compare-before-set-test', compareBeforeSet: true, }); storage.set('key', 'short'); const sizeAfterInitialSet = storage.byteSize; // Set a longer value - byteSize should increase storage.set('key', 'a much longer string value that takes more space'); expect(storage.byteSize).toBeGreaterThan(sizeAfterInitialSet); }); }); describe('MMKV Storage Management', () => { let storage: MMKV; beforeEach(() => { storage = createMMKV({ id: 'storage-management-test' }); storage.clearAll(); }); afterEach(() => { storage.clearAll(); }); describe('Storage Size & Management', () => { it('should track storage byte size correctly', () => { const initialSize = storage.byteSize; storage.set('test-key', 'test-value'); expect(storage.byteSize).toBeGreaterThan(initialSize); const sizeAfterSet = storage.byteSize; storage.set('another-key', 'another-value'); expect(storage.byteSize).toBeGreaterThan(sizeAfterSet); }); it('should track storage key length correctly', () => { const initialLength = storage.length; storage.set('test-key', 'test-value'); expect(storage.length).toStrictEqual(initialLength + 1); const lengthAfterSet = storage.length; storage.set('another-key', 'another-value'); expect(storage.length).toBeGreaterThan(lengthAfterSet); }); it('should handle trim operation', () => { // Add some data for (let i = 0; i < 100; i++) { storage.set(`key-${i}`, `value-${i}`); } const sizeBeforeTrim = storage.byteSize; expect(sizeBeforeTrim).toBeGreaterThan(0); // Remove half the data for (let i = 0; i < 50; i++) { storage.remove(`key-${i}`); } // Trim should clean up unused space storage.trim(); // Verify remaining data is still accessible for (let i = 50; i < 100; i++) { expect(storage.getString(`key-${i}`)).toStrictEqual(`value-${i}`); } }); it('should handle clearAll correctly', () => { // Add various types of data storage.set('string-key', 'string-value'); storage.set('number-key', 123.456); storage.set('boolean-key', true); storage.set('buffer-key', new Uint8Array([1, 2, 3]).buffer); expect(storage.getAllKeys().length).toStrictEqual(4); expect(storage.byteSize).toBeGreaterThan(0); expect(storage.length).toBeGreaterThan(0); storage.clearAll(); expect(storage.getAllKeys()).toEqual([]); expect(storage.contains('string-key')).toBe(false); expect(storage.contains('number-key')).toBe(false); expect(storage.contains('boolean-key')).toBe(false); expect(storage.contains('buffer-key')).toBe(false); expect(storage.length).toBe(0) }); it('should handle storage operations after clearAll', () => { // Add data, clear, then add again storage.set('initial-key', 'initial-value'); expect(storage.getString('initial-key')).toStrictEqual('initial-value'); storage.clearAll(); expect(storage.getString('initial-key')).toBeUndefined(); storage.set('new-key', 'new-value'); expect(storage.getString('new-key')).toStrictEqual('new-value'); expect(storage.getAllKeys()).toEqual(['new-key']); }); }); describe('Performance & Stress Tests', () => { it('should handle rapid consecutive operations', () => { const iterations = 1000; // Rapid writes for (let i = 0; i < iterations; i++) { storage.set(`rapid-${i}`, i); } // Rapid reads for (let i = 0; i < iterations; i++) { expect(storage.getNumber(`rapid-${i}`)).toStrictEqual(i); } // Rapid removes for (let i = 0; i < iterations; i += 2) { storage.remove(`rapid-${i}`); } // Verify remaining data for (let i = 1; i < iterations; i += 2) { expect(storage.getNumber(`rapid-${i}`)).toStrictEqual(i); } }); it('should handle mixed operations efficiently', () => { const operations = 500; for (let i = 0; i < operations; i++) { // Mix of different operations storage.set(`mixed-string-${i}`, `value-${i}`); storage.set(`mixed-number-${i}`, i * 1.5); storage.set(`mixed-boolean-${i}`, i % 2 === 0); if (i % 10 === 0) { storage.getAllKeys(); storage.trim(); } if (i % 3 === 0) { storage.contains(`mixed-string-${i}`); } } // Verify data integrity const keys = storage.getAllKeys(); expect(keys.length).toBeGreaterThan(operations * 2); // At least 2/3 of the keys should exist // Random verification for (let i = 0; i < 50; i++) { const randomIndex = Math.floor(Math.random() * operations); expect(storage.getString(`mixed-string-${randomIndex}`)).toStrictEqual( `value-${randomIndex}`, ); expect(storage.getNumber(`mixed-number-${randomIndex}`)).toStrictEqual( randomIndex * 1.5, ); expect( storage.getBoolean(`mixed-boolean-${randomIndex}`), ).toStrictEqual(randomIndex % 2 === 0); } }); }); }); describe('MMKV Multi-Process Mode', () => { afterEach(() => { try { createMMKV({ id: 'multi-process-test' }).clearAll(); } catch { // Instance might not exist, that's okay } }); it('should create an instance in multi-process mode', () => { const storage = createMMKV({ id: 'multi-process-test', mode: 'multi-process', }); storage.set('key', 'value'); expect(storage.getString('key')).toStrictEqual('value'); }); it('should store and retrieve all value types in multi-process mode', () => { const storage = createMMKV({ id: 'multi-process-test', mode: 'multi-process', }); storage.set('str', 'hello'); storage.set('num', 3.14); storage.set('bool', true); storage.set('buf', new Uint8Array([10, 20, 30]).buffer); expect(storage.getString('str')).toStrictEqual('hello'); expect(storage.getNumber('num')).toStrictEqual(3.14); expect(storage.getBoolean('bool')).toStrictEqual(true); expect(new Uint8Array(storage.getBuffer('buf')!)).toEqual( new Uint8Array([10, 20, 30]) ); }); it('should support remove, contains and clearAll in multi-process mode', () => { const storage = createMMKV({ id: 'multi-process-test', mode: 'multi-process', }); storage.set('a', 'one'); storage.set('b', 'two'); expect(storage.contains('a')).toBe(true); storage.remove('a'); expect(storage.contains('a')).toBe(false); expect(storage.getString('b')).toStrictEqual('two'); storage.clearAll(); expect(storage.getAllKeys()).toEqual([]); }); it('should support encryption in multi-process mode', () => { const storage = createMMKV({ id: 'multi-process-encrypted-test', mode: 'multi-process', encryptionKey: 'secret-key-12345', }); storage.set('secret', 'data'); expect(storage.getString('secret')).toStrictEqual('data'); expect(storage.isEncrypted).toStrictEqual(true); storage.clearAll(); }); }); describe('MMKV Listeners & Observers', () => { let storage: MMKV; beforeEach(() => { storage = createMMKV({ id: 'listener-test' }); storage.clearAll(); }); afterEach(() => { storage.clearAll(); }); describe('Value Change Listeners', () => { it('should trigger listeners on value changes', async () => { const changedKeys: string[] = []; const listener = storage.addOnValueChangedListener(key => { changedKeys.push(key); }); storage.set('test-key-1', 'value1'); storage.set('test-key-2', 42); storage.set('test-key-3', true); // Wait for the listeners to trigger await waitForNextTick(); expect(changedKeys).toContain('test-key-1'); expect(changedKeys).toContain('test-key-2'); expect(changedKeys).toContain('test-key-3'); listener.remove(); }); it('should trigger listeners on value updates', async () => { const changedKeys: string[] = []; const listener = storage.addOnValueChangedListener(key => { changedKeys.push(key); }); const testKey = 'update-test'; storage.set(testKey, 'original'); storage.set(testKey, 'updated'); storage.set(testKey, 'final'); // Wait for the listeners to trigger await waitForNextTick(); const keyChanges = changedKeys.filter(k => k === testKey); expect(keyChanges.length).toStrictEqual(3); listener.remove(); }); it('should trigger listeners on value removal', async () => { const changedKeys: string[] = []; const listener = storage.addOnValueChangedListener(key => { changedKeys.push(key); }); const testKey = 'remove-test'; storage.set(testKey, 'value'); await waitForNextTick(); storage.remove(testKey); // Wait for the listeners to trigger await waitForNextTick(); expect(changedKeys.filter(k => k === testKey).length).toStrictEqual(2); listener.remove(); }); it('should handle multiple listeners correctly', async () => { const listener1Changes: string[] = []; const listener2Changes: string[] = []; const listener1 = storage.addOnValueChangedListener(key => { listener1Changes.push(key); }); const listener2 = storage.addOnValueChangedListener(key => { listener2Changes.push(key); }); storage.set('multi-listener-test', 'value'); // Wait for the listeners to trigger await waitForNextTick(); expect(listener1Changes).toContain('multi-listener-test'); expect(listener2Changes).toContain('multi-listener-test'); listener1.remove(); listener2.remove(); }); it('should stop triggering after listener removal', async () => { const changedKeys: string[] = []; const listener = storage.addOnValueChangedListener(key => { changedKeys.push(key); }); storage.set('before-removal', 'value'); // Wait for the listeners to trigger await waitForNextTick(); expect(changedKeys).toContain('before-removal'); listener.remove(); storage.set('after-removal', 'value'); // Wait for potential listeners to trigger (but they shouldn't) await waitForNextTick(); expect(changedKeys).not.toContain('after-removal'); }); it('should handle listener removal multiple times safely', () => { const listener = storage.addOnValueChangedListener(() => { }); // Should not throw errors listener.remove(); listener.remove(); listener.remove(); }); it('should not trigger listeners for clearAll', async () => { const changedKeys: string[] = []; const listener = storage.addOnValueChangedListener(key => { changedKeys.push(key); }); storage.set('key1', 'value1'); storage.set('key2', 'value2'); // Wait for the listeners to trigger await waitForNextTick(); storage.clearAll(); // Wait for the listeners to trigger await waitForNextTick(); // We did 2x set and a clearAll (clears 2x keys) expect(changedKeys.length).toStrictEqual(4); listener.remove(); }); }); }); describe('Deleting instances and checking if they exist', () => { beforeEach(() => { deleteMMKV('some-instance') deleteMMKV('some-non-existing-instance') }) describe('Checking if an instance exists', () => { it('should exist', () => { createMMKV({ id: 'some-instance' }) const exists = existsMMKV('some-instance') expect(exists).toStrictEqual(true) }) it('should not exist', () => { const exists = existsMMKV('some-non-existing-instance') expect(exists).toStrictEqual(false) }) }) describe('Deleting an instance', () => { it('should delete properly', () => { createMMKV({ id: 'some-instance' }) const wasDeleted = deleteMMKV('some-instance') expect(wasDeleted).toStrictEqual(true) }) it('should delete properly and exists should be false', () => { createMMKV({ id: 'some-instance' }) const wasDeleted = deleteMMKV('some-instance') expect(wasDeleted).toStrictEqual(true) const exists = existsMMKV('some-instance') expect(exists).toStrictEqual(false) }) it('should not delete', () => { const wasDeleted = deleteMMKV('some-non-existing-instance') expect(wasDeleted).toStrictEqual(false) }) }) }) describe('MMKV Error Handling & Edge Cases', () => { let storage: MMKV; beforeEach(() => { storage = createMMKV({ id: 'error-handling-test' }); storage.clearAll(); }); afterEach(() => { storage.clearAll(); }); describe('Error Scenarios', () => { it('should handle invalid key operations gracefully', () => { // Empty string key should throw expect(() => { storage.set('', 'empty-key-value'); }).toThrow() }); it('should handle concurrent operations', () => { // Simulate concurrent operations const promises = []; for (let i = 0; i < 100; i++) { promises.push( Promise.resolve().then(() => { storage.set(`concurrent-${i}`, i); return storage.getNumber(`concurrent-${i}`); }), ); } return Promise.all(promises).then(results => { results.forEach((value, index) => { expect(value).toStrictEqual(index); }); }); }); it('should handle Unicode and special characters', () => { const unicodeTests = [ { key: 'emoji', value: '🚀🎉✨' }, { key: 'chinese', value: '你好世界' }, { key: 'arabic', value: 'مرحبا بالعالم' }, { key: 'russian', value: 'Привет мир' }, { key: 'japanese', value: 'こんにちは世界' }, { key: 'mixed', value: 'Hello 🌍 नमस्ते 🙏' }, ]; unicodeTests.forEach(test => { storage.set(test.key, test.value); expect(storage.getString(test.key)).toStrictEqual(test.value); }); }); it('should handle extreme number values', () => { const extremeNumbers = [ { key: 'max-safe', value: Number.MAX_SAFE_INTEGER }, { key: 'min-safe', value: Number.MIN_SAFE_INTEGER }, { key: 'max-value', value: Number.MAX_VALUE }, { key: 'min-value', value: Number.MIN_VALUE }, { key: 'infinity', value: Infinity }, { key: 'negative-infinity', value: -Infinity }, { key: 'nan', value: NaN }, ]; extremeNumbers.forEach(test => { storage.set(test.key, test.value); const retrieved = storage.getNumber(test.key); if (isNaN(test.value)) { expect(isNaN(retrieved!)).toBe(true); } else { expect(retrieved).toStrictEqual(test.value); } }); }); it('should maintain data integrity across operations', () => { // Create a complex data set const testData = { strings: Array.from({ length: 50 }, (_, i) => ({ key: `str-${i}`, value: `string-value-${i}`, })), numbers: Array.from({ length: 50 }, (_, i) => ({ key: `num-${i}`, value: Math.random() * 1000, })), booleans: Array.from({ length: 50 }, (_, i) => ({ key: `bool-${i}`, value: i % 2 === 0, })), }; // Set all data [...testData.strings, ...testData.numbers, ...testData.booleans].forEach( item => { storage.set(item.key, item.value); }, ); // Perform random operations for (let i = 0; i < 100; i++) { const operation = Math.floor(Math.random() * 4); switch (operation) { case 0: // Random read const randomKey = `str-${Math.floor(Math.random() * 50)}`; storage.getString(randomKey); break; case 1: // Random update const updateKey = `num-${Math.floor(Math.random() * 50)}`; storage.set(updateKey, Math.random() * 2000); break; case 2: // Check contains const checkKey = `bool-${Math.floor(Math.random() * 50)}`; storage.contains(checkKey); break; case 3: // Get all keys storage.getAllKeys(); break; } } // Verify data integrity for strings and booleans (numbers were updated) testData.strings.forEach(item => { expect(storage.getString(item.key)).toStrictEqual(item.value); }); testData.booleans.forEach(item => { expect(storage.getBoolean(item.key)).toStrictEqual(item.value); }); // Verify all keys still exist const allKeys = storage.getAllKeys(); expect(allKeys.length).toStrictEqual(150); }); }); }); ================================================ FILE: example/android/app/build.gradle ================================================ apply plugin: "com.android.application" apply plugin: "org.jetbrains.kotlin.android" apply plugin: "com.facebook.react" /** * This is the configuration block to customize your React Native Android app. * By default you don't need to apply any configuration, just uncomment the lines you need. */ react { /* Folders */ // The root of your project, i.e. where "package.json" lives. Default is '../..' // root = file("../../") // The folder where the react-native NPM package is. Default is ../../node_modules/react-native reactNativeDir = file("../../../node_modules/react-native") // The folder where the react-native Codegen package is. Default is ../../node_modules/@react-native/codegen codegenDir = file("../../../node_modules/@react-native/codegen") // The cli.js file which is the React Native CLI entrypoint. Default is ../../node_modules/react-native/cli.js cliFile = file("../../../node_modules/react-native/cli.js") /* Variants */ // The list of variants to that are debuggable. For those we're going to // skip the bundling of the JS bundle and the assets. By default is just 'debug'. // If you add flavors like lite, prod, etc. you'll have to list your debuggableVariants. // debuggableVariants = ["liteDebug", "prodDebug"] /* Bundling */ // A list containing the node command and its flags. Default is just 'node'. // nodeExecutableAndArgs = ["node"] // // The command to run when bundling. By default is 'bundle' // bundleCommand = "ram-bundle" // // The path to the CLI configuration file. Default is empty. // bundleConfig = file(../rn-cli.config.js) // // The name of the generated asset file containing your JS bundle // bundleAssetName = "MyApplication.android.bundle" // // The entry file for bundle generation. Default is 'index.android.js' or 'index.js' // entryFile = file("../js/MyApplication.android.js") // // A list of extra flags to pass to the 'bundle' commands. // See https://github.com/react-native-community/cli/blob/main/docs/commands.md#bundle // extraPackagerArgs = [] /* Hermes Commands */ // The hermes compiler command to run. By default it is 'hermesc' hermesCommand = "$rootDir/../../node_modules/react-native/sdks/hermesc/%OS-BIN%/hermesc" // // The list of flags to pass to the Hermes compiler. By default is "-O", "-output-source-map" // hermesFlags = ["-O", "-output-source-map"] /* Autolinking */ autolinkLibrariesWithApp() } /** * Set this to true to Run Proguard on Release builds to minify the Java bytecode. */ def enableProguardInReleaseBuilds = false /** * The preferred build flavor of JavaScriptCore (JSC) * * For example, to use the international variant, you can use: * `def jscFlavor = io.github.react-native-community:jsc-android-intl:2026004.+` * * The international variant includes ICU i18n library and necessary data * allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that * give correct results when using with locales other than en-US. Note that * this variant is about 6MiB larger per architecture than default. */ def jscFlavor = 'io.github.react-native-community:jsc-android:2026004.+' android { ndkVersion rootProject.ext.ndkVersion buildToolsVersion rootProject.ext.buildToolsVersion compileSdk rootProject.ext.compileSdkVersion namespace "com.mrousavy.mmkv.example" defaultConfig { applicationId "com.mrousavy.mmkv.example" minSdkVersion rootProject.ext.minSdkVersion targetSdkVersion rootProject.ext.targetSdkVersion versionCode 1 versionName "1.0" } signingConfigs { debug { storeFile file('debug.keystore') storePassword 'android' keyAlias 'androiddebugkey' keyPassword 'android' } } buildTypes { debug { signingConfig signingConfigs.debug } release { // Caution! In production, you need to generate your own keystore file. // see https://reactnative.dev/docs/signed-apk-android. signingConfig signingConfigs.debug minifyEnabled enableProguardInReleaseBuilds proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro" } } } dependencies { // The version of react-native is set by the React Native Gradle Plugin implementation("com.facebook.react:react-android") if (hermesEnabled.toBoolean()) { implementation("com.facebook.react:hermes-android") } else { implementation jscFlavor } } ================================================ FILE: example/android/app/proguard-rules.pro ================================================ # Add project specific ProGuard rules here. # By default, the flags in this file are appended to flags specified # in /usr/local/Cellar/android-sdk/24.3.3/tools/proguard/proguard-android.txt # You can edit the include path and order by changing the proguardFiles # directive in build.gradle. # # For more details, see # http://developer.android.com/guide/developing/tools/proguard.html # Add any project specific keep options here: ================================================ FILE: example/android/app/src/main/AndroidManifest.xml ================================================ ================================================ FILE: example/android/app/src/main/java/com/mrousavy/mmkv/example/MainActivity.kt ================================================ package com.mrousavy.mmkv.example import com.facebook.react.ReactActivity import com.facebook.react.ReactActivityDelegate import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.fabricEnabled import com.facebook.react.defaults.DefaultReactActivityDelegate class MainActivity : ReactActivity() { /** * Returns the name of the main component registered from JavaScript. This is used to schedule * rendering of the component. */ override fun getMainComponentName(): String = "MmkvExample" /** * Returns the instance of the [ReactActivityDelegate]. We use [DefaultReactActivityDelegate] * which allows you to enable New Architecture with a single boolean flags [fabricEnabled] */ override fun createReactActivityDelegate(): ReactActivityDelegate = DefaultReactActivityDelegate(this, mainComponentName, fabricEnabled) } ================================================ FILE: example/android/app/src/main/java/com/mrousavy/mmkv/example/MainApplication.kt ================================================ package com.mrousavy.mmkv.example import android.app.Application import com.facebook.react.PackageList import com.facebook.react.ReactApplication import com.facebook.react.ReactHost import com.facebook.react.ReactNativeApplicationEntryPoint.loadReactNative import com.facebook.react.defaults.DefaultReactHost.getDefaultReactHost class MainApplication : Application(), ReactApplication { override val reactHost: ReactHost by lazy { getDefaultReactHost( context = applicationContext, packageList = PackageList(this).packages.apply { // no extra packages }, ) } override fun onCreate() { super.onCreate() loadReactNative(this) } } ================================================ FILE: example/android/app/src/main/res/drawable/rn_edit_text_material.xml ================================================ ================================================ FILE: example/android/app/src/main/res/values/strings.xml ================================================ MmkvExample ================================================ FILE: example/android/app/src/main/res/values/styles.xml ================================================ ================================================ FILE: example/android/build.gradle ================================================ buildscript { ext { buildToolsVersion = "36.0.0" minSdkVersion = 24 compileSdkVersion = 36 targetSdkVersion = 36 ndkVersion = "27.1.12297006" kotlinVersion = "2.1.20" } repositories { google() mavenCentral() } dependencies { classpath("com.android.tools.build:gradle") classpath("com.facebook.react:react-native-gradle-plugin") classpath("org.jetbrains.kotlin:kotlin-gradle-plugin") } } apply plugin: "com.facebook.react.rootproject" ================================================ FILE: example/android/gradle/wrapper/gradle-wrapper.properties ================================================ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists distributionUrl=https\://services.gradle.org/distributions/gradle-9.0.0-bin.zip networkTimeout=10000 validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists ================================================ FILE: example/android/gradle.properties ================================================ # Project-wide Gradle settings. # IDE (e.g. Android Studio) users: # Gradle settings configured through the IDE *will override* # any settings specified in this file. # For more details on how to configure your build environment visit # http://www.gradle.org/docs/current/userguide/build_environment.html # Specifies the JVM arguments used for the daemon process. # The setting is particularly useful for tweaking memory settings. # Default value: -Xmx512m -XX:MaxMetaspaceSize=256m org.gradle.jvmargs=-Xmx2048m -XX:MaxMetaspaceSize=512m # When configured, Gradle will run in incubating parallel mode. # This option should only be used with decoupled projects. More details, visit # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects # org.gradle.parallel=true # AndroidX package structure to make it clearer which packages are bundled with the # Android operating system, and which are packaged with your app's APK # https://developer.android.com/topic/libraries/support-library/androidx-rn android.useAndroidX=true # Use this property to specify which architecture you want to build. # You can also override it from the CLI using # ./gradlew -PreactNativeArchitectures=x86_64 reactNativeArchitectures=armeabi-v7a,arm64-v8a,x86,x86_64 # Use this property to enable support to the new architecture. # This will allow you to use TurboModules and the Fabric render in # your application. You should enable this flag either if you want # to write custom TurboModules/Fabric components OR use libraries that # are providing them. newArchEnabled=true # Use this property to enable or disable the Hermes JS engine. # If set to false, you will be using JSC instead. hermesEnabled=true # Use this property to enable edge-to-edge display support. # This allows your app to draw behind system bars for an immersive UI. # Note: Only works with ReactActivity and should not be used with custom Activity. edgeToEdgeEnabled=false ================================================ FILE: example/android/gradlew ================================================ #!/bin/sh # # Copyright © 2015-2021 the original authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # SPDX-License-Identifier: Apache-2.0 # ############################################################################## # # Gradle start up script for POSIX generated by Gradle. # # Important for running: # # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is # noncompliant, but you have some other compliant shell such as ksh or # bash, then to run this script, type that shell name before the whole # command line, like: # # ksh Gradle # # Busybox and similar reduced shells will NOT work, because this script # requires all of these POSIX shell features: # * functions; # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», # «${var#prefix}», «${var%suffix}», and «$( cmd )»; # * compound commands having a testable exit status, especially «case»; # * various built-in commands including «command», «set», and «ulimit». # # Important for patching: # # (2) This script targets any POSIX shell, so it avoids extensions provided # by Bash, Ksh, etc; in particular arrays are avoided. # # The "traditional" practice of packing multiple parameters into a # space-separated string is a well documented source of bugs and security # problems, so this is (mostly) avoided, by progressively accumulating # options in "$@", and eventually passing that to Java. # # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; # see the in-line comments for details. # # There are tweaks for specific operating systems such as AIX, CygWin, # Darwin, MinGW, and NonStop. # # (3) This script is generated from the Groovy template # https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt # within the Gradle project. # # You can find Gradle at https://github.com/gradle/gradle/. # ############################################################################## # Attempt to set APP_HOME # Resolve links: $0 may be a link app_path=$0 # Need this for daisy-chained symlinks. while APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path [ -h "$app_path" ] do ls=$( ls -ld "$app_path" ) link=${ls#*' -> '} case $link in #( /*) app_path=$link ;; #( *) app_path=$APP_HOME$link ;; esac done # This is normally unused # shellcheck disable=SC2034 APP_BASE_NAME=${0##*/} # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD=maximum warn () { echo "$*" } >&2 die () { echo echo "$*" echo exit 1 } >&2 # OS specific support (must be 'true' or 'false'). cygwin=false msys=false darwin=false nonstop=false case "$( uname )" in #( CYGWIN* ) cygwin=true ;; #( Darwin* ) darwin=true ;; #( MSYS* | MINGW* ) msys=true ;; #( NONSTOP* ) nonstop=true ;; esac CLASSPATH="\\\"\\\"" # Determine the Java command to use to start the JVM. if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then # IBM's JDK on AIX uses strange locations for the executables JAVACMD=$JAVA_HOME/jre/sh/java else JAVACMD=$JAVA_HOME/bin/java fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else JAVACMD=java if ! command -v java >/dev/null 2>&1 then die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi fi # Increase the maximum file descriptors if we can. if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then case $MAX_FD in #( max*) # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. # shellcheck disable=SC2039,SC3045 MAX_FD=$( ulimit -H -n ) || warn "Could not query maximum file descriptor limit" esac case $MAX_FD in #( '' | soft) :;; #( *) # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. # shellcheck disable=SC2039,SC3045 ulimit -n "$MAX_FD" || warn "Could not set maximum file descriptor limit to $MAX_FD" esac fi # Collect all arguments for the java command, stacking in reverse order: # * args from the command line # * the main class name # * -classpath # * -D...appname settings # * --module-path (only if needed) # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. # For Cygwin or MSYS, switch paths to Windows format before running java if "$cygwin" || "$msys" ; then APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) JAVACMD=$( cygpath --unix "$JAVACMD" ) # Now convert the arguments - kludge to limit ourselves to /bin/sh for arg do if case $arg in #( -*) false ;; # don't mess with options #( /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath [ -e "$t" ] ;; #( *) false ;; esac then arg=$( cygpath --path --ignore --mixed "$arg" ) fi # Roll the args list around exactly as many times as the number of # args, so each arg winds up back in the position where it started, but # possibly modified. # # NB: a `for` loop captures its iteration list before it begins, so # changing the positional parameters here affects neither the number of # iterations, nor the values presented in `arg`. shift # remove old arg set -- "$@" "$arg" # push replacement arg done fi # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' # Collect all arguments for the java command: # * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, # and any embedded shellness will be escaped. # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be # treated as '${Hostname}' itself on the command line. set -- \ "-Dorg.gradle.appname=$APP_BASE_NAME" \ -classpath "$CLASSPATH" \ -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ "$@" # Stop when "xargs" is not available. if ! command -v xargs >/dev/null 2>&1 then die "xargs is not available" fi # Use "xargs" to parse quoted args. # # With -n1 it outputs one arg per line, with the quotes and backslashes removed. # # In Bash we could simply go: # # readarray ARGS < <( xargs -n1 <<<"$var" ) && # set -- "${ARGS[@]}" "$@" # # but POSIX shell has neither arrays nor command substitution, so instead we # post-process each arg (as a line of input to sed) to backslash-escape any # character that might be a shell metacharacter, then use eval to reverse # that process (while maintaining the separation between arguments), and wrap # the whole thing up as a single "set" statement. # # This will of course break if any of these variables contains a newline or # an unmatched quote. # eval "set -- $( printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | xargs -n1 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | tr '\n' ' ' )" '"$@"' exec "$JAVACMD" "$@" ================================================ FILE: example/android/gradlew.bat ================================================ @REM Copyright (c) Meta Platforms, Inc. and affiliates. @REM @REM This source code is licensed under the MIT license found in the @REM LICENSE file in the root directory of this source tree. @rem @rem Copyright 2015 the original author or authors. @rem @rem Licensed under the Apache License, Version 2.0 (the "License"); @rem you may not use this file except in compliance with the License. @rem You may obtain a copy of the License at @rem @rem https://www.apache.org/licenses/LICENSE-2.0 @rem @rem Unless required by applicable law or agreed to in writing, software @rem distributed under the License is distributed on an "AS IS" BASIS, @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @rem See the License for the specific language governing permissions and @rem limitations under the License. @rem @rem SPDX-License-Identifier: Apache-2.0 @rem @if "%DEBUG%"=="" @echo off @rem ########################################################################## @rem @rem Gradle startup script for Windows @rem @rem ########################################################################## @rem Set local scope for the variables with windows NT shell if "%OS%"=="Windows_NT" setlocal set DIRNAME=%~dp0 if "%DIRNAME%"=="" set DIRNAME=. @rem This is normally unused set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% @rem Resolve any "." and ".." in APP_HOME to make it shorter. for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" @rem Find java.exe if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 if %ERRORLEVEL% equ 0 goto execute echo. 1>&2 echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 echo. 1>&2 echo Please set the JAVA_HOME variable in your environment to match the 1>&2 echo location of your Java installation. 1>&2 goto fail :findJavaFromJavaHome set JAVA_HOME=%JAVA_HOME:"=% set JAVA_EXE=%JAVA_HOME%/bin/java.exe if exist "%JAVA_EXE%" goto execute echo. 1>&2 echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 echo. 1>&2 echo Please set the JAVA_HOME variable in your environment to match the 1>&2 echo location of your Java installation. 1>&2 goto fail :execute @rem Setup the command line set CLASSPATH= @rem Execute Gradle "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* :end @rem End local scope for the variables with windows NT shell if %ERRORLEVEL% equ 0 goto mainEnd :fail rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem the _cmd.exe /c_ return code! set EXIT_CODE=%ERRORLEVEL% if %EXIT_CODE% equ 0 set EXIT_CODE=1 if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% exit /b %EXIT_CODE% :mainEnd if "%OS%"=="Windows_NT" endlocal :omega ================================================ FILE: example/android/settings.gradle ================================================ pluginManagement { includeBuild("../../node_modules/@react-native/gradle-plugin") } plugins { id("com.facebook.react.settings") } extensions.configure(com.facebook.react.ReactSettingsExtension){ ex -> ex.autolinkLibrariesFromCommand() } rootProject.name = 'MmkvExample' include ':app' includeBuild('../../node_modules/@react-native/gradle-plugin') ================================================ FILE: example/app.json ================================================ { "name": "MmkvExample", "displayName": "MmkvExample" } ================================================ FILE: example/babel.config.js ================================================ module.exports = { presets: [ 'module:@react-native/babel-preset', 'react-native-harness/babel-preset', ], }; ================================================ FILE: example/index.js ================================================ /** * @format */ import { AppRegistry } from 'react-native'; import App from './src/App'; import { name as appName } from './app.json'; AppRegistry.registerComponent(appName, () => App); ================================================ FILE: example/ios/.xcode.env ================================================ # This `.xcode.env` file is versioned and is used to source the environment # used when running script phases inside Xcode. # To customize your local environment, you can create an `.xcode.env.local` # file that is not versioned. # NODE_BINARY variable contains the PATH to the node executable. # # Customize the NODE_BINARY variable here. # For example, to use nvm with brew, add the following line # . "$(brew --prefix nvm)/nvm.sh" --no-use export NODE_BINARY=$(command -v node) ================================================ FILE: example/ios/MmkvExample/AppDelegate.swift ================================================ import UIKit import React import React_RCTAppDelegate import ReactAppDependencyProvider @main class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var reactNativeDelegate: ReactNativeDelegate? var reactNativeFactory: RCTReactNativeFactory? func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil ) -> Bool { let delegate = ReactNativeDelegate() let factory = RCTReactNativeFactory(delegate: delegate) delegate.dependencyProvider = RCTAppDependencyProvider() reactNativeDelegate = delegate reactNativeFactory = factory window = UIWindow(frame: UIScreen.main.bounds) factory.startReactNative( withModuleName: "MmkvExample", in: window, launchOptions: launchOptions ) return true } } class ReactNativeDelegate: RCTDefaultReactNativeFactoryDelegate { override func sourceURL(for bridge: RCTBridge) -> URL? { self.bundleURL() } override func bundleURL() -> URL? { #if DEBUG RCTBundleURLProvider.sharedSettings().jsBundleURL(forBundleRoot: "index") #else Bundle.main.url(forResource: "main", withExtension: "jsbundle") #endif } } ================================================ FILE: example/ios/MmkvExample/Images.xcassets/AppIcon.appiconset/Contents.json ================================================ { "images" : [ { "idiom" : "iphone", "scale" : "2x", "size" : "20x20" }, { "idiom" : "iphone", "scale" : "3x", "size" : "20x20" }, { "idiom" : "iphone", "scale" : "2x", "size" : "29x29" }, { "idiom" : "iphone", "scale" : "3x", "size" : "29x29" }, { "idiom" : "iphone", "scale" : "2x", "size" : "40x40" }, { "idiom" : "iphone", "scale" : "3x", "size" : "40x40" }, { "idiom" : "iphone", "scale" : "2x", "size" : "60x60" }, { "idiom" : "iphone", "scale" : "3x", "size" : "60x60" }, { "idiom" : "ios-marketing", "scale" : "1x", "size" : "1024x1024" } ], "info" : { "author" : "xcode", "version" : 1 } } ================================================ FILE: example/ios/MmkvExample/Images.xcassets/Contents.json ================================================ { "info" : { "version" : 1, "author" : "xcode" } } ================================================ FILE: example/ios/MmkvExample/Info.plist ================================================ CADisableMinimumFrameDurationOnPhone CFBundleDevelopmentRegion en CFBundleDisplayName MmkvExample CFBundleExecutable $(EXECUTABLE_NAME) CFBundleIdentifier $(PRODUCT_BUNDLE_IDENTIFIER) CFBundleInfoDictionaryVersion 6.0 CFBundleName $(PRODUCT_NAME) CFBundlePackageType APPL CFBundleShortVersionString $(MARKETING_VERSION) CFBundleSignature ???? CFBundleVersion $(CURRENT_PROJECT_VERSION) LSRequiresIPhoneOS NSAppTransportSecurity NSAllowsArbitraryLoads NSAllowsLocalNetworking NSLocationWhenInUseUsageDescription RCTNewArchEnabled UILaunchStoryboardName LaunchScreen UIRequiredDeviceCapabilities arm64 UISupportedInterfaceOrientations UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight UIViewControllerBasedStatusBarAppearance ================================================ FILE: example/ios/MmkvExample/LaunchScreen.storyboard ================================================ ================================================ FILE: example/ios/MmkvExample/PrivacyInfo.xcprivacy ================================================ NSPrivacyAccessedAPITypes NSPrivacyAccessedAPIType NSPrivacyAccessedAPICategoryFileTimestamp NSPrivacyAccessedAPITypeReasons C617.1 NSPrivacyAccessedAPIType NSPrivacyAccessedAPICategoryUserDefaults NSPrivacyAccessedAPITypeReasons CA92.1 NSPrivacyAccessedAPIType NSPrivacyAccessedAPICategorySystemBootTime NSPrivacyAccessedAPITypeReasons 35F9.1 NSPrivacyCollectedDataTypes NSPrivacyTracking ================================================ FILE: example/ios/MmkvExample.xcodeproj/project.pbxproj ================================================ // !$*UTF8*$! { archiveVersion = 1; classes = { }; objectVersion = 54; objects = { /* Begin PBXBuildFile section */ 0C80B921A6F3F58F76C31292 /* libPods-MmkvExample.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 5DCACB8F33CDC322A6C60F78 /* libPods-MmkvExample.a */; }; 13B07FBF1A68108700A75B9A /* Images.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 13B07FB51A68108700A75B9A /* Images.xcassets */; }; 761780ED2CA45674006654EE /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 761780EC2CA45674006654EE /* AppDelegate.swift */; }; 81AB9BB82411601600AC10FF /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 81AB9BB72411601600AC10FF /* LaunchScreen.storyboard */; }; D14B608BF8079920A6778F45 /* PrivacyInfo.xcprivacy in Resources */ = {isa = PBXBuildFile; fileRef = 13B07FB81A68108700A75B9A /* PrivacyInfo.xcprivacy */; }; /* End PBXBuildFile section */ /* Begin PBXFileReference section */ 13B07F961A680F5B00A75B9A /* MmkvExample.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = MmkvExample.app; sourceTree = BUILT_PRODUCTS_DIR; }; 13B07FB51A68108700A75B9A /* Images.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; name = Images.xcassets; path = MmkvExample/Images.xcassets; sourceTree = ""; }; 13B07FB61A68108700A75B9A /* Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = Info.plist; path = MmkvExample/Info.plist; sourceTree = ""; }; 13B07FB81A68108700A75B9A /* PrivacyInfo.xcprivacy */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = PrivacyInfo.xcprivacy; path = MmkvExample/PrivacyInfo.xcprivacy; sourceTree = ""; }; 3B4392A12AC88292D35C810B /* Pods-MmkvExample.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-MmkvExample.debug.xcconfig"; path = "Target Support Files/Pods-MmkvExample/Pods-MmkvExample.debug.xcconfig"; sourceTree = ""; }; 5709B34CF0A7D63546082F79 /* Pods-MmkvExample.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-MmkvExample.release.xcconfig"; path = "Target Support Files/Pods-MmkvExample/Pods-MmkvExample.release.xcconfig"; sourceTree = ""; }; 5DCACB8F33CDC322A6C60F78 /* libPods-MmkvExample.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = "libPods-MmkvExample.a"; sourceTree = BUILT_PRODUCTS_DIR; }; 761780EC2CA45674006654EE /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = AppDelegate.swift; path = MmkvExample/AppDelegate.swift; sourceTree = ""; }; 81AB9BB72411601600AC10FF /* LaunchScreen.storyboard */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.storyboard; name = LaunchScreen.storyboard; path = MmkvExample/LaunchScreen.storyboard; sourceTree = ""; }; ED297162215061F000B7C4FE /* JavaScriptCore.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = JavaScriptCore.framework; path = System/Library/Frameworks/JavaScriptCore.framework; sourceTree = SDKROOT; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ 13B07F8C1A680F5B00A75B9A /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( 0C80B921A6F3F58F76C31292 /* libPods-MmkvExample.a in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ 13B07FAE1A68108700A75B9A /* MmkvExample */ = { isa = PBXGroup; children = ( 13B07FB51A68108700A75B9A /* Images.xcassets */, 761780EC2CA45674006654EE /* AppDelegate.swift */, 13B07FB61A68108700A75B9A /* Info.plist */, 81AB9BB72411601600AC10FF /* LaunchScreen.storyboard */, 13B07FB81A68108700A75B9A /* PrivacyInfo.xcprivacy */, ); name = MmkvExample; sourceTree = ""; }; 2D16E6871FA4F8E400B85C8A /* Frameworks */ = { isa = PBXGroup; children = ( ED297162215061F000B7C4FE /* JavaScriptCore.framework */, 5DCACB8F33CDC322A6C60F78 /* libPods-MmkvExample.a */, ); name = Frameworks; sourceTree = ""; }; 832341AE1AAA6A7D00B99B32 /* Libraries */ = { isa = PBXGroup; children = ( ); name = Libraries; sourceTree = ""; }; 83CBB9F61A601CBA00E9B192 = { isa = PBXGroup; children = ( 13B07FAE1A68108700A75B9A /* MmkvExample */, 832341AE1AAA6A7D00B99B32 /* Libraries */, 83CBBA001A601CBA00E9B192 /* Products */, 2D16E6871FA4F8E400B85C8A /* Frameworks */, BBD78D7AC51CEA395F1C20DB /* Pods */, ); indentWidth = 2; sourceTree = ""; tabWidth = 2; usesTabs = 0; }; 83CBBA001A601CBA00E9B192 /* Products */ = { isa = PBXGroup; children = ( 13B07F961A680F5B00A75B9A /* MmkvExample.app */, ); name = Products; sourceTree = ""; }; BBD78D7AC51CEA395F1C20DB /* Pods */ = { isa = PBXGroup; children = ( 3B4392A12AC88292D35C810B /* Pods-MmkvExample.debug.xcconfig */, 5709B34CF0A7D63546082F79 /* Pods-MmkvExample.release.xcconfig */, ); path = Pods; sourceTree = ""; }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ 13B07F861A680F5B00A75B9A /* MmkvExample */ = { isa = PBXNativeTarget; buildConfigurationList = 13B07F931A680F5B00A75B9A /* Build configuration list for PBXNativeTarget "MmkvExample" */; buildPhases = ( C38B50BA6285516D6DCD4F65 /* [CP] Check Pods Manifest.lock */, 13B07F871A680F5B00A75B9A /* Sources */, 13B07F8C1A680F5B00A75B9A /* Frameworks */, 13B07F8E1A680F5B00A75B9A /* Resources */, 00DD1BFF1BD5951E006B06BC /* Bundle React Native code and images */, 00EEFC60759A1932668264C0 /* [CP] Embed Pods Frameworks */, E235C05ADACE081382539298 /* [CP] Copy Pods Resources */, ); buildRules = ( ); dependencies = ( ); name = MmkvExample; productName = MmkvExample; productReference = 13B07F961A680F5B00A75B9A /* MmkvExample.app */; productType = "com.apple.product-type.application"; }; /* End PBXNativeTarget section */ /* Begin PBXProject section */ 83CBB9F71A601CBA00E9B192 /* Project object */ = { isa = PBXProject; attributes = { LastUpgradeCheck = 1210; TargetAttributes = { 13B07F861A680F5B00A75B9A = { LastSwiftMigration = 1120; }; }; }; buildConfigurationList = 83CBB9FA1A601CBA00E9B192 /* Build configuration list for PBXProject "MmkvExample" */; compatibilityVersion = "Xcode 12.0"; developmentRegion = en; hasScannedForEncodings = 0; knownRegions = ( en, Base, ); mainGroup = 83CBB9F61A601CBA00E9B192; productRefGroup = 83CBBA001A601CBA00E9B192 /* Products */; projectDirPath = ""; projectRoot = ""; targets = ( 13B07F861A680F5B00A75B9A /* MmkvExample */, ); }; /* End PBXProject section */ /* Begin PBXResourcesBuildPhase section */ 13B07F8E1A680F5B00A75B9A /* Resources */ = { isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( 81AB9BB82411601600AC10FF /* LaunchScreen.storyboard in Resources */, 13B07FBF1A68108700A75B9A /* Images.xcassets in Resources */, D14B608BF8079920A6778F45 /* PrivacyInfo.xcprivacy in Resources */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXResourcesBuildPhase section */ /* Begin PBXShellScriptBuildPhase section */ 00DD1BFF1BD5951E006B06BC /* Bundle React Native code and images */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( "$(SRCROOT)/.xcode.env.local", "$(SRCROOT)/.xcode.env", ); name = "Bundle React Native code and images"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; shellScript = "set -e\n\nWITH_ENVIRONMENT=\"$REACT_NATIVE_PATH/scripts/xcode/with-environment.sh\"\nREACT_NATIVE_XCODE=\"$REACT_NATIVE_PATH/scripts/react-native-xcode.sh\"\n\n/bin/sh -c \"$WITH_ENVIRONMENT $REACT_NATIVE_XCODE\"\n"; }; 00EEFC60759A1932668264C0 /* [CP] Embed Pods Frameworks */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputFileListPaths = ( "${PODS_ROOT}/Target Support Files/Pods-MmkvExample/Pods-MmkvExample-frameworks-${CONFIGURATION}-input-files.xcfilelist", ); name = "[CP] Embed Pods Frameworks"; outputFileListPaths = ( "${PODS_ROOT}/Target Support Files/Pods-MmkvExample/Pods-MmkvExample-frameworks-${CONFIGURATION}-output-files.xcfilelist", ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-MmkvExample/Pods-MmkvExample-frameworks.sh\"\n"; showEnvVarsInLog = 0; }; C38B50BA6285516D6DCD4F65 /* [CP] Check Pods Manifest.lock */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputFileListPaths = ( ); inputPaths = ( "${PODS_PODFILE_DIR_PATH}/Podfile.lock", "${PODS_ROOT}/Manifest.lock", ); name = "[CP] Check Pods Manifest.lock"; outputFileListPaths = ( ); outputPaths = ( "$(DERIVED_FILE_DIR)/Pods-MmkvExample-checkManifestLockResult.txt", ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; showEnvVarsInLog = 0; }; E235C05ADACE081382539298 /* [CP] Copy Pods Resources */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputFileListPaths = ( "${PODS_ROOT}/Target Support Files/Pods-MmkvExample/Pods-MmkvExample-resources-${CONFIGURATION}-input-files.xcfilelist", ); name = "[CP] Copy Pods Resources"; outputFileListPaths = ( "${PODS_ROOT}/Target Support Files/Pods-MmkvExample/Pods-MmkvExample-resources-${CONFIGURATION}-output-files.xcfilelist", ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-MmkvExample/Pods-MmkvExample-resources.sh\"\n"; showEnvVarsInLog = 0; }; /* End PBXShellScriptBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ 13B07F871A680F5B00A75B9A /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( 761780ED2CA45674006654EE /* AppDelegate.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXSourcesBuildPhase section */ /* Begin XCBuildConfiguration section */ 13B07F941A680F5B00A75B9A /* Debug */ = { isa = XCBuildConfiguration; baseConfigurationReference = 3B4392A12AC88292D35C810B /* Pods-MmkvExample.debug.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; CLANG_ENABLE_MODULES = YES; CURRENT_PROJECT_VERSION = 1; DEVELOPMENT_TEAM = CJW62Q77E7; ENABLE_BITCODE = NO; INFOPLIST_FILE = MmkvExample/Info.plist; IPHONEOS_DEPLOYMENT_TARGET = 15.1; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", ); MARKETING_VERSION = 1.0; OTHER_LDFLAGS = ( "$(inherited)", "-ObjC", "-lc++", ); PRODUCT_BUNDLE_IDENTIFIER = com.mrousavy.mmkv.example; PRODUCT_NAME = MmkvExample; SWIFT_ENABLE_EXPLICIT_MODULES = NO; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; SWIFT_VERSION = 5.0; VERSIONING_SYSTEM = "apple-generic"; }; name = Debug; }; 13B07F951A680F5B00A75B9A /* Release */ = { isa = XCBuildConfiguration; baseConfigurationReference = 5709B34CF0A7D63546082F79 /* Pods-MmkvExample.release.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; CLANG_ENABLE_MODULES = YES; CURRENT_PROJECT_VERSION = 1; DEVELOPMENT_TEAM = CJW62Q77E7; INFOPLIST_FILE = MmkvExample/Info.plist; IPHONEOS_DEPLOYMENT_TARGET = 15.1; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", ); MARKETING_VERSION = 1.0; OTHER_LDFLAGS = ( "$(inherited)", "-ObjC", "-lc++", ); PRODUCT_BUNDLE_IDENTIFIER = com.mrousavy.mmkv.example; PRODUCT_NAME = MmkvExample; SWIFT_ENABLE_EXPLICIT_MODULES = NO; SWIFT_VERSION = 5.0; VERSIONING_SYSTEM = "apple-generic"; }; name = Release; }; 83CBBA201A601CBA00E9B192 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES; CLANG_CXX_LANGUAGE_STANDARD = "c++20"; CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_ARC = YES; CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; CLANG_WARN_BOOL_CONVERSION = YES; CLANG_WARN_COMMA = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; CLANG_WARN_STRICT_PROTOTYPES = YES; CLANG_WARN_SUSPICIOUS_MOVE = YES; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; COPY_PHASE_STRIP = NO; ENABLE_STRICT_OBJC_MSGSEND = YES; ENABLE_TESTABILITY = YES; "EXCLUDED_ARCHS[sdk=iphonesimulator*]" = ""; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_DYNAMIC_NO_PIC = NO; GCC_NO_COMMON_BLOCKS = YES; GCC_OPTIMIZATION_LEVEL = 0; GCC_PREPROCESSOR_DEFINITIONS = ( "DEBUG=1", "$(inherited)", ); GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_WARN_64_TO_32_BIT_CONVERSION = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; GCC_WARN_UNDECLARED_SELECTOR = YES; GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; IPHONEOS_DEPLOYMENT_TARGET = 15.1; LD_RUNPATH_SEARCH_PATHS = ( /usr/lib/swift, "$(inherited)", ); LIBRARY_SEARCH_PATHS = ( "\"$(SDKROOT)/usr/lib/swift\"", "\"$(TOOLCHAIN_DIR)/usr/lib/swift/$(PLATFORM_NAME)\"", "\"$(inherited)\"", ); MTL_ENABLE_DEBUG_INFO = YES; ONLY_ACTIVE_ARCH = YES; OTHER_CPLUSPLUSFLAGS = ( "$(OTHER_CFLAGS)", "-DFOLLY_NO_CONFIG", "-DFOLLY_MOBILE=1", "-DFOLLY_USE_LIBCPP=1", "-DFOLLY_CFG_NO_COROUTINES=1", "-DFOLLY_HAVE_CLOCK_GETTIME=1", ); REACT_NATIVE_PATH = "${PODS_ROOT}/../../../node_modules/react-native"; SDKROOT = iphoneos; SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) DEBUG"; SWIFT_ENABLE_EXPLICIT_MODULES = NO; USE_HERMES = true; }; name = Debug; }; 83CBBA211A601CBA00E9B192 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES; CLANG_CXX_LANGUAGE_STANDARD = "c++20"; CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_ARC = YES; CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; CLANG_WARN_BOOL_CONVERSION = YES; CLANG_WARN_COMMA = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; CLANG_WARN_STRICT_PROTOTYPES = YES; CLANG_WARN_SUSPICIOUS_MOVE = YES; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; COPY_PHASE_STRIP = YES; ENABLE_NS_ASSERTIONS = NO; ENABLE_STRICT_OBJC_MSGSEND = YES; "EXCLUDED_ARCHS[sdk=iphonesimulator*]" = ""; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_NO_COMMON_BLOCKS = YES; GCC_WARN_64_TO_32_BIT_CONVERSION = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; GCC_WARN_UNDECLARED_SELECTOR = YES; GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; IPHONEOS_DEPLOYMENT_TARGET = 15.1; LD_RUNPATH_SEARCH_PATHS = ( /usr/lib/swift, "$(inherited)", ); LIBRARY_SEARCH_PATHS = ( "\"$(SDKROOT)/usr/lib/swift\"", "\"$(TOOLCHAIN_DIR)/usr/lib/swift/$(PLATFORM_NAME)\"", "\"$(inherited)\"", ); MTL_ENABLE_DEBUG_INFO = NO; OTHER_CPLUSPLUSFLAGS = ( "$(OTHER_CFLAGS)", "-DFOLLY_NO_CONFIG", "-DFOLLY_MOBILE=1", "-DFOLLY_USE_LIBCPP=1", "-DFOLLY_CFG_NO_COROUTINES=1", "-DFOLLY_HAVE_CLOCK_GETTIME=1", ); REACT_NATIVE_PATH = "${PODS_ROOT}/../../../node_modules/react-native"; SDKROOT = iphoneos; SWIFT_ENABLE_EXPLICIT_MODULES = NO; USE_HERMES = true; VALIDATE_PRODUCT = YES; }; name = Release; }; /* End XCBuildConfiguration section */ /* Begin XCConfigurationList section */ 13B07F931A680F5B00A75B9A /* Build configuration list for PBXNativeTarget "MmkvExample" */ = { isa = XCConfigurationList; buildConfigurations = ( 13B07F941A680F5B00A75B9A /* Debug */, 13B07F951A680F5B00A75B9A /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; 83CBB9FA1A601CBA00E9B192 /* Build configuration list for PBXProject "MmkvExample" */ = { isa = XCConfigurationList; buildConfigurations = ( 83CBBA201A601CBA00E9B192 /* Debug */, 83CBBA211A601CBA00E9B192 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; /* End XCConfigurationList section */ }; rootObject = 83CBB9F71A601CBA00E9B192 /* Project object */; } ================================================ FILE: example/ios/MmkvExample.xcodeproj/xcshareddata/xcschemes/MmkvExample.xcscheme ================================================ ================================================ FILE: example/ios/MmkvExample.xcworkspace/contents.xcworkspacedata ================================================ ================================================ FILE: example/ios/Podfile ================================================ # Resolve react_native_pods.rb with node to allow for hoisting require Pod::Executable.execute_command('node', ['-p', 'require.resolve( "react-native/scripts/react_native_pods.rb", {paths: [process.argv[1]]}, )', __dir__]).strip platform :ios, min_ios_version_supported prepare_react_native_project! linkage = ENV['USE_FRAMEWORKS'] if linkage != nil Pod::UI.puts "Configuring Pod with #{linkage}ally linked Frameworks".green use_frameworks! :linkage => linkage.to_sym end target 'MmkvExample' do config = use_native_modules! use_react_native!( :path => config[:reactNativePath], # An absolute path to your application root. :app_path => "#{Pod::Config.instance.installation_root}/.." ) post_install do |installer| # https://github.com/facebook/react-native/blob/main/packages/react-native/scripts/react_native_pods.rb#L197-L202 react_native_post_install( installer, config[:reactNativePath], :mac_catalyst_enabled => false, # :ccache_enabled => true ) end end ================================================ FILE: example/jest.config.js ================================================ module.exports = { projects: [ { displayName: 'react-native-harness', preset: 'react-native-harness', testMatch: [ '/__tests__/**/*.(test|spec|harness).(js|jsx|ts|tsx)', ], }, ], }; ================================================ FILE: example/metro.config.js ================================================ const { getDefaultConfig, mergeConfig } = require('@react-native/metro-config'); const path = require('path'); /** * Metro configuration * https://reactnative.dev/docs/metro * * @type {import('@react-native/metro-config').MetroConfig} */ const config = { watchFolders: [path.resolve(__dirname, '..')], }; module.exports = mergeConfig(getDefaultConfig(__dirname), config); ================================================ FILE: example/package.json ================================================ { "name": "mmkv-example", "version": "4.3.0", "private": true, "scripts": { "android": "react-native run-android", "ios": "react-native run-ios", "lint": "eslint \"**/*.{js,ts,tsx}\" --fix", "lint-ci": "eslint \"**/*.{js,ts,tsx}\" -f @jamesacarr/github-actions", "start": "react-native start", "test": "jest", "test:harness": "react-native-harness", "bundle-install": "bundle install", "pods": "bundle install && cd ios && bundle exec pod install", "build:android-release": "cd android && ./gradlew assembleRelease --no-daemon" }, "dependencies": { "@react-native/new-app-screen": "0.82.0", "react": "19.1.1", "react-native": "0.82.0", "react-native-mmkv": "*", "react-native-nitro-modules": "0.35.0", "react-native-safe-area-context": "^5.5.2" }, "devDependencies": { "@babel/core": "^7.25.2", "@babel/preset-env": "^7.25.3", "@babel/runtime": "^7.28.3", "@react-native-community/cli": "20.0.0", "@react-native-community/cli-platform-android": "20.0.0", "@react-native-community/cli-platform-ios": "20.0.0", "@react-native/babel-preset": "0.82.0", "@react-native/eslint-config": "0.82.0", "@react-native/metro-config": "0.82.0", "@react-native/typescript-config": "0.82.0", "react-native-harness": "1.0.0-alpha.19", "@react-native-harness/jest": "1.0.0-alpha.19", "@react-native-harness/platform-android": "1.0.0-alpha.19", "@react-native-harness/platform-apple": "1.0.0-alpha.19", "@types/jest": "^29.5.13", "@types/react": "^19.1.1", "@types/react-test-renderer": "19.1.0", "eslint": "^8.19.0", "jest": "^30.2.0", "prettier": "2.8.8", "react-test-renderer": "19.1.1", "typescript": "^5.8.3" }, "engines": { "node": ">=20" } } ================================================ FILE: example/rn-harness.config.mjs ================================================ import { androidPlatform, androidEmulator, } from '@react-native-harness/platform-android'; import { applePlatform, appleSimulator, } from '@react-native-harness/platform-apple'; const config = { entryPoint: './index.js', appRegistryComponentName: 'MmkvExample', runners: [ androidPlatform({ name: 'android', device: androidEmulator('Pixel_8_API_35', { apiLevel: 35, profile: 'pixel_6', diskSize: '1G', heapSize: '1G', }), bundleId: 'com.mrousavy.mmkv.example', }), applePlatform({ name: 'ios', device: appleSimulator('iPhone 16 Pro', '18.6'), bundleId: 'com.mrousavy.mmkv.example', }), ], defaultRunner: 'android', bridgeTimeout: 120000, resetEnvironmentBetweenTestFiles: true, unstable__skipAlreadyIncludedModules: false, }; export default config; ================================================ FILE: example/src/App.tsx ================================================ import * as React from 'react'; import { StyleSheet, View, TextInput, Alert, Button, Text, useColorScheme, } from 'react-native'; import { createMMKV, useMMKVListener, useMMKVString, useMMKVKeys } from 'react-native-mmkv'; const storage = createMMKV(); export default function App() { const [text, setText] = React.useState(''); const [key, setKey] = React.useState(''); const keys = useMMKVKeys(storage) const colorScheme = useColorScheme(); const [example, setExample] = useMMKVString('nitrooooo'); useMMKVListener((k) => { console.log(`${k} changed! New size: ${storage.byteSize}`); }); const save = React.useCallback(() => { if (key == null || key.length < 1) { Alert.alert('Empty key!', 'Enter a key first.'); return; } try { console.log('setting...'); storage.set(key, text); console.log('set.'); } catch (e) { console.error('Error:', e); Alert.alert('Failed to set value for key "test"!', JSON.stringify(e)); } }, [key, text]); const read = React.useCallback(() => { if (key == null || key.length < 1) { Alert.alert('Empty key!', 'Enter a key first.'); return; } try { console.log('getting...'); const value = storage.getString(key); console.log('got:', value); Alert.alert('Result', `"${key}" = "${value}"`); } catch (e) { console.error('Error:', e); Alert.alert('Failed to get value for key "test"!', JSON.stringify(e)); } }, [key]); React.useEffect(() => { console.log(`Value of useMMKVString: ${example}`); const interval = setInterval(() => { setExample((val) => { return val === 'nitrooooo' ? undefined : 'nitrooooo'; }); }, 1000); return () => { clearInterval(interval); }; }, [example, setExample]); const isDark = colorScheme === 'dark'; const dynamicStyles = createDynamicStyles(isDark); return ( Available Keys: {keys.join(', ')} Key: Value: