├── .github ├── FUNDING.yml ├── dependabot.yml ├── funding-octocat.svg └── workflows │ ├── build-android.yml │ ├── build-ios.yml │ ├── validate-cpp.yml │ └── validate-js.yml ├── .gitignore ├── .gitmodules ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── docs ├── HOOKS.md ├── LISTENERS.md ├── MIGRATE_FROM_ASYNC_STORAGE.md ├── WRAPPER_JOTAI.md ├── WRAPPER_MOBX.md ├── WRAPPER_MOBXPERSIST.md ├── WRAPPER_REACT_QUERY.md ├── WRAPPER_RECOIL.md ├── WRAPPER_REDUX.md └── WRAPPER_ZUSTAND_PERSIST_MIDDLEWARE.md ├── package ├── .clang-format ├── .eslintrc.js ├── .gitattributes ├── .gitignore ├── .nvmrc ├── .prettierrc.js ├── .watchmanconfig ├── README.md ├── android │ ├── CMakeLists.txt │ ├── build.gradle │ ├── gradle.properties │ └── src │ │ └── main │ │ ├── AndroidManifest.xml │ │ ├── cpp │ │ └── AndroidLogger.cpp │ │ └── java │ │ └── com │ │ └── mrousavy │ │ └── mmkv │ │ ├── MmkvPackage.java │ │ └── MmkvPlatformContextModule.java ├── babel.config.js ├── cpp │ ├── MMKVManagedBuffer.h │ ├── MmkvHostObject.cpp │ ├── MmkvHostObject.h │ ├── MmkvLogger.h │ ├── NativeMmkvModule.cpp │ └── NativeMmkvModule.h ├── example │ ├── .bundle │ │ └── config │ ├── .watchmanconfig │ ├── Gemfile │ ├── Gemfile.lock │ ├── README.md │ ├── android │ │ ├── app │ │ │ ├── build.gradle │ │ │ ├── debug.keystore │ │ │ ├── proguard-rules.pro │ │ │ └── src │ │ │ │ ├── debug │ │ │ │ └── AndroidManifest.xml │ │ │ │ └── main │ │ │ │ ├── AndroidManifest.xml │ │ │ │ ├── java │ │ │ │ └── com │ │ │ │ │ └── mrousavy │ │ │ │ │ └── mmkvexample │ │ │ │ │ ├── MainActivity.kt │ │ │ │ │ └── MainApplication.kt │ │ │ │ └── res │ │ │ │ ├── drawable │ │ │ │ └── rn_edit_text_material.xml │ │ │ │ ├── mipmap-hdpi │ │ │ │ ├── ic_launcher.png │ │ │ │ └── ic_launcher_round.png │ │ │ │ ├── mipmap-mdpi │ │ │ │ ├── ic_launcher.png │ │ │ │ └── ic_launcher_round.png │ │ │ │ ├── mipmap-xhdpi │ │ │ │ ├── ic_launcher.png │ │ │ │ └── ic_launcher_round.png │ │ │ │ ├── mipmap-xxhdpi │ │ │ │ ├── ic_launcher.png │ │ │ │ └── ic_launcher_round.png │ │ │ │ ├── mipmap-xxxhdpi │ │ │ │ ├── ic_launcher.png │ │ │ │ └── ic_launcher_round.png │ │ │ │ └── values │ │ │ │ ├── strings.xml │ │ │ │ └── styles.xml │ │ ├── build.gradle │ │ ├── gradle.properties │ │ ├── gradle │ │ │ └── wrapper │ │ │ │ ├── gradle-wrapper.jar │ │ │ │ └── gradle-wrapper.properties │ │ ├── gradlew │ │ ├── gradlew.bat │ │ └── settings.gradle │ ├── app.json │ ├── babel.config.js │ ├── index.js │ ├── ios │ │ ├── .xcode.env │ │ ├── .xcode.env.local │ │ ├── AppDelegate.swift │ │ ├── File.cpp │ │ ├── File.swift │ │ ├── MmkvExample-Bridging-Header.h │ │ ├── MmkvExample.xcodeproj │ │ │ ├── project.pbxproj │ │ │ └── xcshareddata │ │ │ │ └── xcschemes │ │ │ │ └── MmkvExample.xcscheme │ │ ├── MmkvExample.xcworkspace │ │ │ ├── contents.xcworkspacedata │ │ │ └── xcshareddata │ │ │ │ └── IDEWorkspaceChecks.plist │ │ ├── MmkvExample │ │ │ ├── Images.xcassets │ │ │ │ ├── AppIcon.appiconset │ │ │ │ │ └── Contents.json │ │ │ │ └── Contents.json │ │ │ ├── Info.plist │ │ │ └── LaunchScreen.storyboard │ │ ├── Podfile │ │ ├── Podfile.lock │ │ └── PrivacyInfo.xcprivacy │ ├── jest.config.js │ ├── metro.config.js │ ├── package.json │ ├── react-native.config.js │ ├── src │ │ └── App.tsx │ ├── test │ │ └── MMKV.test.ts │ ├── tsconfig.json │ └── yarn.lock ├── img │ ├── banner-dark.png │ ├── banner-light.png │ └── benchmark_1000_get.png ├── ios │ ├── AppleLogger.mm │ ├── MmkvOnLoad.mm │ ├── MmkvPlatformContext.h │ └── MmkvPlatformContextModule.mm ├── lefthook.yml ├── package.json ├── react-native-mmkv.podspec ├── react-native.config.js ├── scripts │ └── clang-format.sh ├── src │ ├── MMKV.ts │ ├── MemoryWarningListener.ts │ ├── MemoryWarningListener.web.ts │ ├── ModuleNotFoundError.ts │ ├── NativeMmkv.ts │ ├── NativeMmkvPlatformContext.ts │ ├── PlatformChecker.ts │ ├── Types.ts │ ├── __tests__ │ │ └── hooks.test.tsx │ ├── createMMKV.mock.ts │ ├── createMMKV.ts │ ├── createMMKV.web.ts │ ├── createTextEncoder.ts │ ├── hooks.ts │ └── index.ts ├── tsconfig.json └── yarn.lock └── tea.yaml /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: mrousavy 4 | patreon: # Replace with a single Patreon username 5 | open_collective: # Replace with a single Open Collective username 6 | ko_fi: mrousavy 7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel 8 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry 9 | liberapay: # Replace with a single Liberapay username 10 | issuehunt: # Replace with a single IssueHunt username 11 | otechie: # Replace with a single Otechie username 12 | custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] 13 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | 3 | updates: 4 | - package-ecosystem: "github-actions" 5 | directory: "/" 6 | schedule: 7 | interval: "weekly" 8 | labels: 9 | - "dependencies" 10 | - package-ecosystem: "gradle" 11 | directory: "/package/android/" 12 | schedule: 13 | interval: "weekly" 14 | labels: 15 | - "dependencies" 16 | - package-ecosystem: "gitsubmodule" 17 | directory: "/package" 18 | schedule: 19 | interval: "weekly" 20 | labels: 21 | - "dependencies" 22 | -------------------------------------------------------------------------------- /.github/funding-octocat.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 7 | 11 | 15 | 19 | 23 | 27 | 31 | 35 | 39 | 43 | 47 | 51 | 55 | 59 | 63 | 67 | 71 | 75 | 79 | 83 | 87 | 91 | 95 | 99 | 100 | 101 | 105 | 109 | 113 | 117 | 121 | 125 | 129 | 133 | 134 | 137 | 140 | 143 | 144 | 148 | 152 | 153 | 154 | 155 | 168 | 169 |
170 | This library helped you?
Consider sponsoring!
171 |
172 |
173 |
174 | -------------------------------------------------------------------------------- /.github/workflows/build-android.yml: -------------------------------------------------------------------------------- 1 | name: Build Android 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | paths: 8 | - '.github/workflows/build-android.yml' 9 | - 'package/android/**' 10 | - 'package/cpp/**' 11 | - 'package/MMKV/**' 12 | - 'package/yarn.lock' 13 | - 'package/example/android/**' 14 | - 'package/example/yarn.lock' 15 | pull_request: 16 | paths: 17 | - '.github/workflows/build-android.yml' 18 | - 'package/android/**' 19 | - 'package/cpp/**' 20 | - 'package/MMKV/**' 21 | - 'package/yarn.lock' 22 | - 'package/example/android/**' 23 | - 'package/example/yarn.lock' 24 | 25 | jobs: 26 | build_example: 27 | name: Build Android Example App 28 | runs-on: ubuntu-latest 29 | defaults: 30 | run: 31 | working-directory: package/ 32 | steps: 33 | - uses: actions/checkout@v4 34 | 35 | - name: Setup JDK 17 36 | uses: actions/setup-java@v4 37 | with: 38 | distribution: 'zulu' 39 | java-version: 17 40 | java-package: jdk 41 | 42 | - name: Get yarn cache directory path 43 | id: yarn-cache-dir-path 44 | run: echo "::set-output name=dir::$(yarn cache dir)" 45 | - name: Restore node_modules from cache 46 | uses: actions/cache@v4 47 | id: yarn-cache 48 | with: 49 | path: ${{ steps.yarn-cache-dir-path.outputs.dir }} 50 | key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }} 51 | restore-keys: | 52 | ${{ runner.os }}-yarn- 53 | - name: Install node_modules 54 | run: yarn install --frozen-lockfile 55 | - name: Install node_modules for example/ 56 | run: yarn install --frozen-lockfile --cwd example 57 | 58 | - name: Restore Gradle cache 59 | uses: actions/cache@v4 60 | with: 61 | path: | 62 | ~/.gradle/caches 63 | ~/.gradle/wrapper 64 | key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties') }} 65 | restore-keys: | 66 | ${{ runner.os }}-gradle- 67 | - name: Run Gradle Build for example/android/ 68 | run: cd example/android && ./gradlew assembleDebug --build-cache && cd ../.. 69 | -------------------------------------------------------------------------------- /.github/workflows/build-ios.yml: -------------------------------------------------------------------------------- 1 | name: Build iOS 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | paths: 8 | - '.github/workflows/build-ios.yml' 9 | - 'package/cpp/**' 10 | - 'package/ios/**' 11 | - 'package/*.podspec' 12 | - 'package/example/ios/**' 13 | - 'package/MMKV/**' 14 | pull_request: 15 | paths: 16 | - '.github/workflows/build-ios.yml' 17 | - 'package/cpp/**' 18 | - 'package/ios/**' 19 | - 'package/*.podspec' 20 | - 'package/example/ios/**' 21 | - 'package/MMKV/**' 22 | 23 | jobs: 24 | build_example: 25 | name: Build iOS Example App 26 | runs-on: macOS-latest 27 | defaults: 28 | run: 29 | working-directory: package/example/ios 30 | steps: 31 | - uses: actions/checkout@v4 32 | 33 | - name: Get yarn cache directory path 34 | id: yarn-cache-dir-path 35 | run: echo "::set-output name=dir::$(yarn cache dir)" 36 | - name: Restore node_modules from cache 37 | uses: actions/cache@v4 38 | id: yarn-cache 39 | with: 40 | path: ${{ steps.yarn-cache-dir-path.outputs.dir }} 41 | key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }} 42 | restore-keys: | 43 | ${{ runner.os }}-yarn- 44 | - name: Install node_modules 45 | run: yarn install --frozen-lockfile --cwd ../.. 46 | - name: Install node_modules for example/ 47 | run: yarn install --frozen-lockfile --cwd .. 48 | 49 | - name: Restore buildcache 50 | uses: mikehardy/buildcache-action@v2 51 | continue-on-error: true 52 | 53 | - name: Setup Ruby (bundle) 54 | uses: ruby/setup-ruby@v1 55 | with: 56 | ruby-version: 2.6 57 | bundler-cache: true 58 | working-directory: package/example/ios 59 | 60 | - name: Restore Pods cache 61 | uses: actions/cache@v4 62 | with: 63 | path: | 64 | package/example/ios/Pods 65 | ~/Library/Caches/CocoaPods 66 | ~/.cocoapods 67 | key: ${{ runner.os }}-pods-${{ hashFiles('**/Podfile.lock') }} 68 | restore-keys: | 69 | ${{ runner.os }}-pods- 70 | - name: Install Pods 71 | run: yarn pods 72 | - name: Install xcpretty 73 | run: gem install xcpretty 74 | - name: Build App 75 | run: "set -o pipefail && xcodebuild \ 76 | CC=clang CPLUSPLUS=clang++ LD=clang LDPLUSPLUS=clang++ \ 77 | -derivedDataPath build -UseModernBuildSystem=YES \ 78 | -workspace MmkvExample.xcworkspace \ 79 | -scheme MmkvExample \ 80 | -sdk iphonesimulator \ 81 | -configuration Debug \ 82 | -destination 'platform=iOS Simulator,name=iPhone 15' \ 83 | build \ 84 | CODE_SIGNING_ALLOWED=NO | xcpretty" 85 | -------------------------------------------------------------------------------- /.github/workflows/validate-cpp.yml: -------------------------------------------------------------------------------- 1 | name: Validate C++ 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | paths: 8 | - '.github/workflows/validate-cpp.yml' 9 | - 'package/cpp/**' 10 | - 'package/android/src/main/cpp/**' 11 | - 'package/ios/**' 12 | pull_request: 13 | paths: 14 | - '.github/workflows/validate-cpp.yml' 15 | - 'package/cpp/**' 16 | - 'package/android/src/main/cpp/**' 17 | - 'package/ios/**' 18 | 19 | jobs: 20 | lint: 21 | name: Check clang-format 22 | runs-on: ubuntu-latest 23 | strategy: 24 | matrix: 25 | path: 26 | - 'package/cpp' 27 | - 'package/android/src/main/cpp' 28 | - 'package/ios' 29 | steps: 30 | - uses: actions/checkout@v4 31 | - name: Run clang-format style check 32 | uses: jidicula/clang-format-action@v4.13.0 33 | with: 34 | clang-format-version: '16' 35 | check-path: ${{ matrix.path }} 36 | 37 | -------------------------------------------------------------------------------- /.github/workflows/validate-js.yml: -------------------------------------------------------------------------------- 1 | name: Validate JS 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | paths: 8 | - '.github/workflows/validate-js.yml' 9 | - 'package/src/**' 10 | - 'package/*.json' 11 | - 'package/*.js' 12 | - 'package/*.lock' 13 | - 'package/example/src/**' 14 | - 'package/example/*.json' 15 | - 'package/example/*.js' 16 | - 'package/example/*.lock' 17 | - 'package/example/*.tsx' 18 | pull_request: 19 | paths: 20 | - '.github/workflows/validate-js.yml' 21 | - 'package/src/**' 22 | - 'package/*.json' 23 | - 'package/*.js' 24 | - 'package/*.lock' 25 | - 'package/example/src/**' 26 | - 'package/example/*.json' 27 | - 'package/example/*.js' 28 | - 'package/example/*.lock' 29 | - 'package/example/*.tsx' 30 | 31 | jobs: 32 | compile: 33 | name: Compile JS (tsc) 34 | runs-on: ubuntu-latest 35 | defaults: 36 | run: 37 | working-directory: package/ 38 | steps: 39 | - uses: actions/checkout@v4 40 | 41 | - name: Install reviewdog 42 | uses: reviewdog/action-setup@v1 43 | 44 | - name: Get yarn cache directory path 45 | id: yarn-cache-dir-path 46 | run: echo "::set-output name=dir::$(yarn cache dir)" 47 | - name: Restore node_modules from cache 48 | uses: actions/cache@v4 49 | id: yarn-cache 50 | with: 51 | path: ${{ steps.yarn-cache-dir-path.outputs.dir }} 52 | key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }} 53 | restore-keys: | 54 | ${{ runner.os }}-yarn- 55 | 56 | - name: Install node_modules 57 | run: yarn install --frozen-lockfile 58 | - name: Install node_modules (example/) 59 | run: yarn install --frozen-lockfile --cwd example 60 | 61 | - name: Run TypeScript # Reviewdog tsc errorformat: %f:%l:%c - error TS%n: %m 62 | run: | 63 | yarn typescript | reviewdog -name="tsc" -efm="%f(%l,%c): error TS%n: %m" -reporter="github-pr-review" -filter-mode="nofilter" -fail-on-error -tee 64 | env: 65 | REVIEWDOG_GITHUB_API_TOKEN: ${{ secrets.GITHUB_TOKEN }} 66 | 67 | - name: Run TypeScript in example/ # Reviewdog tsc errorformat: %f:%l:%c - error TS%n: %m 68 | run: | 69 | cd example && yarn typescript | reviewdog -name="tsc" -efm="%f(%l,%c): error TS%n: %m" -reporter="github-pr-review" -filter-mode="nofilter" -fail-on-error -tee && cd .. 70 | env: 71 | REVIEWDOG_GITHUB_API_TOKEN: ${{ secrets.GITHUB_TOKEN }} 72 | 73 | lint: 74 | name: Lint JS (eslint, prettier) 75 | runs-on: ubuntu-latest 76 | defaults: 77 | run: 78 | working-directory: package/ 79 | steps: 80 | - uses: actions/checkout@v4 81 | 82 | - name: Get yarn cache directory path 83 | id: yarn-cache-dir-path 84 | run: echo "::set-output name=dir::$(yarn cache dir)" 85 | - name: Restore node_modules from cache 86 | uses: actions/cache@v4 87 | id: yarn-cache 88 | with: 89 | path: ${{ steps.yarn-cache-dir-path.outputs.dir }} 90 | key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }} 91 | restore-keys: | 92 | ${{ runner.os }}-yarn- 93 | 94 | - name: Install node_modules 95 | run: yarn install --frozen-lockfile 96 | - name: Install node_modules (example/) 97 | run: yarn install --frozen-lockfile --cwd example 98 | 99 | - name: Run ESLint 100 | run: yarn lint -f @jamesacarr/github-actions 101 | 102 | - name: Run ESLint with auto-fix 103 | run: yarn lint --fix 104 | 105 | - name: Verify no files have changed after auto-fix 106 | run: git diff --exit-code HEAD 107 | 108 | test: 109 | name: Test JS 110 | runs-on: ubuntu-latest 111 | defaults: 112 | run: 113 | working-directory: package/ 114 | steps: 115 | - uses: actions/checkout@v4 116 | 117 | - name: Get yarn cache directory path 118 | id: yarn-cache-dir-path 119 | run: echo "::set-output name=dir::$(yarn cache dir)" 120 | - name: Restore node_modules from cache 121 | uses: actions/cache@v4 122 | id: yarn-cache 123 | with: 124 | path: ${{ steps.yarn-cache-dir-path.outputs.dir }} 125 | key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }} 126 | restore-keys: | 127 | ${{ runner.os }}-yarn- 128 | 129 | - name: Install node_modules 130 | run: yarn install --frozen-lockfile 131 | 132 | - name: Install node_modules (example/) 133 | run: yarn install --frozen-lockfile --cwd example 134 | 135 | - name: Run Jest 136 | run: yarn test 137 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | **/node_modules/ 3 | 4 | # no yarn/npm in the root repo! 5 | /package-lock.json 6 | /yarn.lock 7 | 8 | # when switching from v2 -> v3 branches 9 | /example 10 | /ios 11 | /android 12 | /lib 13 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "package/MMKV"] 2 | path = package/MMKV 3 | url = https://github.com/Tencent/MMKV 4 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | 2 | # Contributor Covenant Code of Conduct 3 | 4 | ## Our Pledge 5 | 6 | We as members, contributors, and leaders pledge to make participation in our 7 | community a harassment-free experience for everyone, regardless of age, body 8 | size, visible or invisible disability, ethnicity, sex characteristics, gender 9 | identity and expression, level of experience, education, socio-economic status, 10 | nationality, personal appearance, race, caste, color, religion, or sexual 11 | identity and orientation. 12 | 13 | We pledge to act and interact in ways that contribute to an open, welcoming, 14 | diverse, inclusive, and healthy community. 15 | 16 | ## Our Standards 17 | 18 | Examples of behavior that contributes to a positive environment for our 19 | community include: 20 | 21 | * Demonstrating empathy and kindness toward other people 22 | * Being respectful of differing opinions, viewpoints, and experiences 23 | * Giving and gracefully accepting constructive feedback 24 | * Accepting responsibility and apologizing to those affected by our mistakes, 25 | and learning from the experience 26 | * Focusing on what is best not just for us as individuals, but for the overall 27 | community 28 | 29 | Examples of unacceptable behavior include: 30 | 31 | * The use of sexualized language or imagery, and sexual attention or advances of 32 | any kind 33 | * Trolling, insulting or derogatory comments, and personal or political attacks 34 | * Public or private harassment 35 | * Publishing others' private information, such as a physical or email address, 36 | without their explicit permission 37 | * Other conduct which could reasonably be considered inappropriate in a 38 | professional setting 39 | 40 | ## Enforcement Responsibilities 41 | 42 | Community leaders are responsible for clarifying and enforcing our standards of 43 | acceptable behavior and will take appropriate and fair corrective action in 44 | response to any behavior that they deem inappropriate, threatening, offensive, 45 | or harmful. 46 | 47 | Community leaders have the right and responsibility to remove, edit, or reject 48 | comments, commits, code, wiki edits, issues, and other contributions that are 49 | not aligned to this Code of Conduct, and will communicate reasons for moderation 50 | decisions when appropriate. 51 | 52 | ## Scope 53 | 54 | This Code of Conduct applies within all community spaces, and also applies when 55 | an individual is officially representing the community in public spaces. 56 | Examples of representing our community include using an official e-mail address, 57 | posting via an official social media account, or acting as an appointed 58 | representative at an online or offline event. 59 | 60 | ## Enforcement 61 | 62 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 63 | reported to the community leaders responsible for enforcement at 64 | [INSERT CONTACT METHOD]. 65 | All complaints will be reviewed and investigated promptly and fairly. 66 | 67 | All community leaders are obligated to respect the privacy and security of the 68 | reporter of any incident. 69 | 70 | ## Enforcement Guidelines 71 | 72 | Community leaders will follow these Community Impact Guidelines in determining 73 | the consequences for any action they deem in violation of this Code of Conduct: 74 | 75 | ### 1. Correction 76 | 77 | **Community Impact**: Use of inappropriate language or other behavior deemed 78 | unprofessional or unwelcome in the community. 79 | 80 | **Consequence**: A private, written warning from community leaders, providing 81 | clarity around the nature of the violation and an explanation of why the 82 | behavior was inappropriate. A public apology may be requested. 83 | 84 | ### 2. Warning 85 | 86 | **Community Impact**: A violation through a single incident or series of 87 | actions. 88 | 89 | **Consequence**: A warning with consequences for continued behavior. No 90 | interaction with the people involved, including unsolicited interaction with 91 | those enforcing the Code of Conduct, for a specified period of time. This 92 | includes avoiding interactions in community spaces as well as external channels 93 | like social media. Violating these terms may lead to a temporary or permanent 94 | ban. 95 | 96 | ### 3. Temporary Ban 97 | 98 | **Community Impact**: A serious violation of community standards, including 99 | sustained inappropriate behavior. 100 | 101 | **Consequence**: A temporary ban from any sort of interaction or public 102 | communication with the community for a specified period of time. No public or 103 | private interaction with the people involved, including unsolicited interaction 104 | with those enforcing the Code of Conduct, is allowed during this period. 105 | Violating these terms may lead to a permanent ban. 106 | 107 | ### 4. Permanent Ban 108 | 109 | **Community Impact**: Demonstrating a pattern of violation of community 110 | standards, including sustained inappropriate behavior, harassment of an 111 | individual, or aggression toward or disparagement of classes of individuals. 112 | 113 | **Consequence**: A permanent ban from any sort of public interaction within the 114 | community. 115 | 116 | ## Attribution 117 | 118 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], 119 | version 2.1, available at 120 | [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1]. 121 | 122 | Community Impact Guidelines were inspired by 123 | [Mozilla's code of conduct enforcement ladder][Mozilla CoC]. 124 | 125 | For answers to common questions about this code of conduct, see the FAQ at 126 | [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at 127 | [https://www.contributor-covenant.org/translations][translations]. 128 | 129 | [homepage]: https://www.contributor-covenant.org 130 | [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html 131 | [Mozilla CoC]: https://github.com/mozilla/diversity 132 | [FAQ]: https://www.contributor-covenant.org/faq 133 | [translations]: https://www.contributor-covenant.org/translations 134 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | Contributions are always welcome, no matter how large or small! 4 | 5 | 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). 6 | 7 | ## Development workflow 8 | 9 | To get started with the project, run `npm i` in the `package/` directory to install the required dependencies for each package: 10 | 11 | ```sh 12 | yarn 13 | ``` 14 | 15 | The [example app](/example/) demonstrates usage of the library. You need to run it to test any changes you make. 16 | 17 | 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. 18 | 19 | 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`. 20 | 21 | To edit the Java or Kotlin files, open `example/android` in Android studio and find the source files at `react-native-mmkv` under `Android`. 22 | 23 | You can use various commands from the `package/` directory to work with the project. 24 | 25 | To start the packager: 26 | 27 | ```sh 28 | yarn example start 29 | ``` 30 | 31 | To run the example app on Android: 32 | 33 | ```sh 34 | yarn example android 35 | ``` 36 | 37 | To run the example app on iOS: 38 | 39 | ```sh 40 | yarn example ios 41 | ``` 42 | 43 | To confirm that the app is running with the new architecture, you can check the Metro logs for a message like this: 44 | 45 | ```sh 46 | Running "MmkvExample" with {"fabric":true,"initialProps":{"concurrentRoot":true},"rootTag":1} 47 | ``` 48 | 49 | Note the `"fabric":true` and `"concurrentRoot":true` properties. 50 | 51 | Make sure your code passes TypeScript and ESLint. Run the following to verify: 52 | 53 | ```sh 54 | yarn typecheck 55 | yarn lint 56 | ``` 57 | 58 | To fix formatting errors, run the following: 59 | 60 | ```sh 61 | yarn lint --fix 62 | ``` 63 | 64 | Remember to add tests for your change if possible. Run the unit tests by: 65 | 66 | ```sh 67 | yarn test 68 | ``` 69 | 70 | ### Commit message convention 71 | 72 | We follow the [conventional commits specification](https://www.conventionalcommits.org/en) for our commit messages: 73 | 74 | - `fix`: bug fixes, e.g. fix crash due to deprecated method. 75 | - `feat`: new features, e.g. add new method to the module. 76 | - `refactor`: code refactor, e.g. migrate from class components to hooks. 77 | - `docs`: changes into documentation, e.g. add usage example for the module.. 78 | - `test`: adding or updating tests, e.g. add integration tests using detox. 79 | - `chore`: tooling changes, e.g. change CI config. 80 | 81 | Our pre-commit hooks verify that your commit message matches this format when committing. 82 | 83 | ### Linting and tests 84 | 85 | [ESLint](https://eslint.org/), [Prettier](https://prettier.io/), [TypeScript](https://www.typescriptlang.org/) 86 | 87 | 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. 88 | 89 | Our pre-commit hooks verify that the linter and tests pass when committing. 90 | 91 | ### Publishing to npm 92 | 93 | 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. 94 | 95 | To publish new versions, run the following: 96 | 97 | ```sh 98 | yarn release 99 | ``` 100 | 101 | ### Scripts 102 | 103 | The `package.json` file contains various scripts for common tasks: 104 | 105 | - `yarn`: setup project by installing dependencies. 106 | - `yarn typecheck`: type-check files with TypeScript. 107 | - `yarn lint`: lint files with ESLint. 108 | - `yarn test`: run unit tests with Jest. 109 | - `yarn example start`: start the Metro server for the example app. 110 | - `yarn example android`: run the example app on Android. 111 | - `yarn example ios`: run the example app on iOS. 112 | 113 | ### Sending a pull request 114 | 115 | > **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). 116 | 117 | When you're sending a pull request: 118 | 119 | - Prefer small pull requests focused on one change. 120 | - Verify that linters and tests are passing. 121 | - Review the documentation to make sure it looks good. 122 | - Follow the pull request template when opening a pull request. 123 | - For pull requests that change the API or implementation, discuss with maintainers first by opening an issue. 124 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2024 Marc Rousavy 4 | Permission is hereby granted, free of charge, to any person obtaining a copy 5 | of this software and associated documentation files (the "Software"), to deal 6 | in the Software without restriction, including without limitation the rights 7 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | copies of the Software, and to permit persons to whom the Software is 9 | furnished to do so, subject to the following conditions: 10 | 11 | The above copyright notice and this permission notice shall be included in all 12 | copies or substantial portions of the Software. 13 | 14 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | SOFTWARE. 21 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | react-native-mmkv 6 | 7 | 8 | 9 |
10 |

MMKV

11 |

The fastest key/value storage for React Native.

12 |
13 | 14 |
15 | 16 | 17 | 18 |
19 | 20 | 21 | 22 |
23 | 24 | This library helped you? Consider sponsoring! 25 | 26 |
27 |
28 | 29 | 30 | * **MMKV** is an efficient, small mobile key-value storage framework developed by WeChat. See [Tencent/MMKV](https://github.com/Tencent/MMKV) for more information 31 | * **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. 32 | 33 | ## Features 34 | 35 | * **Get** and **set** strings, booleans, numbers and ArrayBuffers 36 | * **Fully synchronous** calls, no async/await, no Promises, no Bridge. 37 | * **Encryption** support (secure storage) 38 | * **Multiple instances** support (separate user-data with global data) 39 | * **Customizable storage location** 40 | * **High performance** because everything is **written in C++** 41 | * **~30x faster than AsyncStorage** 42 | * 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 43 | * **iOS**, **Android** and **Web** support 44 | * Easy to use **React Hooks** API 45 | 46 | ## react-native-mmkv V3 47 | 48 | > [!IMPORTANT] 49 | > react-native-mmkv V3 is now a pure C++ TurboModule, and **requires the new architecture to be enabled**. (react-native 0.75+) 50 | > - 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)) 51 | > - 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. 52 | > - If you cannot use the new architecture yet, downgrade to react-native-mmkv 2.x.x for now. 53 | 54 | ## Benchmark 55 | 56 | [StorageBenchmark](https://github.com/mrousavy/StorageBenchmark) compares popular storage libraries against each other by reading a value from storage for 1000 times: 57 | 58 |
59 | 60 | 61 | 62 |

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

66 |
67 | 68 | ## Installation 69 | 70 | ### React Native 71 | 72 | ```sh 73 | yarn add react-native-mmkv 74 | cd ios && pod install 75 | ``` 76 | 77 | ### Expo 78 | 79 | ```sh 80 | npx expo install react-native-mmkv 81 | npx expo prebuild 82 | ``` 83 | 84 | ## Usage 85 | 86 | ### Create a new instance 87 | 88 | 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. 89 | 90 | #### Default 91 | 92 | ```js 93 | import { MMKV } from 'react-native-mmkv' 94 | 95 | export const storage = new MMKV() 96 | ``` 97 | 98 | This creates a new storage instance using the default MMKV storage ID (`mmkv.default`). 99 | 100 | #### App Groups or Extensions 101 | 102 | 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. 103 | See [Configuring App Groups](https://developer.apple.com/documentation/xcode/configuring-app-groups). 104 | 105 | #### Customize 106 | 107 | ```js 108 | import { MMKV, Mode } from 'react-native-mmkv' 109 | 110 | export const storage = new MMKV({ 111 | id: `user-${userId}-storage`, 112 | path: `${USER_DIRECTORY}/storage`, 113 | encryptionKey: 'hunter2', 114 | mode: Mode.MULTI_PROCESS, 115 | readOnly: false 116 | }) 117 | ``` 118 | 119 | 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. 120 | 121 | The following values can be configured: 122 | 123 | * `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'`) 124 | * `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)) 125 | * `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)) 126 | * `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). 127 | * `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. 128 | 129 | ### Set 130 | 131 | ```js 132 | storage.set('user.name', 'Marc') 133 | storage.set('user.age', 21) 134 | storage.set('is-mmkv-fast-asf', true) 135 | ``` 136 | 137 | ### Get 138 | 139 | ```js 140 | const username = storage.getString('user.name') // 'Marc' 141 | const age = storage.getNumber('user.age') // 21 142 | const isMmkvFastAsf = storage.getBoolean('is-mmkv-fast-asf') // true 143 | ``` 144 | 145 | ### Hooks 146 | 147 | ```js 148 | const [username, setUsername] = useMMKVString('user.name') 149 | const [age, setAge] = useMMKVNumber('user.age') 150 | const [isMmkvFastAsf, setIsMmkvFastAf] = useMMKVBoolean('is-mmkv-fast-asf') 151 | ``` 152 | 153 | ### Keys 154 | 155 | ```js 156 | // checking if a specific key exists 157 | const hasUsername = storage.contains('user.name') 158 | 159 | // getting all keys 160 | const keys = storage.getAllKeys() // ['user.name', 'user.age', 'is-mmkv-fast-asf'] 161 | 162 | // delete a specific key + value 163 | storage.delete('user.name') 164 | 165 | // delete all keys 166 | storage.clearAll() 167 | ``` 168 | 169 | ### Objects 170 | 171 | ```js 172 | const user = { 173 | username: 'Marc', 174 | age: 21 175 | } 176 | 177 | // Serialize the object into a JSON string 178 | storage.set('user', JSON.stringify(user)) 179 | 180 | // Deserialize the JSON string into an object 181 | const jsonUser = storage.getString('user') // { 'username': 'Marc', 'age': 21 } 182 | const userObject = JSON.parse(jsonUser) 183 | ``` 184 | 185 | ### Encryption 186 | 187 | ```js 188 | // encrypt all data with a private key 189 | storage.recrypt('hunter2') 190 | 191 | // remove encryption 192 | storage.recrypt(undefined) 193 | ``` 194 | 195 | ### Buffers 196 | 197 | ```js 198 | const buffer = new ArrayBuffer(3) 199 | const dataWriter = new Uint8Array(buffer) 200 | dataWriter[0] = 1 201 | dataWriter[1] = 100 202 | dataWriter[2] = 255 203 | storage.set('someToken', buffer) 204 | 205 | const buffer = storage.getBuffer('someToken') 206 | console.log(buffer) // [1, 100, 255] 207 | ``` 208 | 209 | ### Size 210 | 211 | ```js 212 | // get size of MMKV storage in bytes 213 | const size = storage.size 214 | if (size >= 4096) { 215 | // clean unused keys and clear memory cache 216 | storage.trim() 217 | } 218 | ``` 219 | 220 | ## Testing with Jest or Vitest 221 | 222 | 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. 223 | 224 | ## Documentation 225 | 226 | * [Hooks](./docs/HOOKS.md) 227 | * [Value-change Listeners](./docs/LISTENERS.md) 228 | * [Migrate from AsyncStorage](./docs/MIGRATE_FROM_ASYNC_STORAGE.md) 229 | * [Using MMKV with redux-persist](./docs/WRAPPER_REDUX.md) 230 | * [Using MMKV with recoil](./docs/WRAPPER_RECOIL.md) 231 | * [Using MMKV with mobx-persist-storage](./docs/WRAPPER_MOBX.md) 232 | * [Using MMKV with mobx-persist](./docs/WRAPPER_MOBXPERSIST.md) 233 | * [Using MMKV with zustand persist-middleware](./docs/WRAPPER_ZUSTAND_PERSIST_MIDDLEWARE.md) 234 | * [Using MMKV with jotai](./docs/WRAPPER_JOTAI.md) 235 | * [Using MMKV with react-query](./docs/WRAPPER_REACT_QUERY.md) 236 | * [How is this library different from **react-native-mmkv-storage**?](https://github.com/mrousavy/react-native-mmkv/issues/100#issuecomment-886477361) 237 | 238 | ## LocalStorage and In-Memory Storage (Web) 239 | 240 | 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. 241 | 242 | ## Limitations 243 | 244 | - react-native-mmkv V3 requires react-native 0.74 or higher. 245 | - react-native-mmkv V3 requires [the new architecture](https://reactnative.dev/docs/the-new-architecture/landing-page)/TurboModules to be enabled. 246 | - 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). 247 | 248 | ## Integrations 249 | 250 | ### Flipper 251 | 252 | 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. 253 | 254 | ### Reactotron 255 | 256 | 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) 257 | 258 | ## Community Discord 259 | 260 | [**Join the Margelo Community Discord**](https://margelo.com/discord) to chat about react-native-mmkv or other Margelo libraries. 261 | 262 | ## Adopting at scale 263 | 264 | react-native-mmkv is provided _as is_, I work on it in my free time. 265 | 266 | 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. 267 | 268 | ## Contributing 269 | 270 | See the [contributing guide](CONTRIBUTING.md) to learn how to contribute to the repository and the development workflow. 271 | 272 | ## License 273 | 274 | MIT 275 | -------------------------------------------------------------------------------- /docs/HOOKS.md: -------------------------------------------------------------------------------- 1 | # Hooks 2 | 3 | react-native-mmkv provides an easy to use React-Hooks API to be used in Function Components. 4 | 5 | ## Reactively use individual keys 6 | 7 | ```tsx 8 | function App() { 9 | const [username, setUsername] = useMMKVString("user.name") 10 | const [age, setAge] = useMMKVNumber("user.age") 11 | const [isPremiumUser, setIsPremiumUser] = useMMKVBoolean("user.isPremium") 12 | const [privateKey, setPrivateKey] = useMMKVBuffer("user.privateKey") 13 | } 14 | ``` 15 | 16 | ## Clear a key 17 | 18 | ```tsx 19 | function App() { 20 | const [username, setUsername] = useMMKVString("user.name") 21 | // ... 22 | const onLogout = useCallback(() => { 23 | setUsername(undefined) 24 | }, []) 25 | } 26 | ``` 27 | 28 | ## Objects 29 | 30 | ```tsx 31 | type User = { 32 | id: string 33 | username: string 34 | age: number 35 | } 36 | 37 | function App() { 38 | const [user, setUser] = useMMKVObject("user") 39 | } 40 | ``` 41 | 42 | ## Reactively use an MMKV Instance 43 | 44 | ```tsx 45 | function App() { 46 | const storage = useMMKV() 47 | // ... 48 | const onLogin = useCallback((username) => { 49 | storage.set("user.name", "Marc") 50 | }, [storage]) 51 | } 52 | ``` 53 | 54 | ## Reactively use individual keys from custom instances 55 | 56 | ```tsx 57 | function App() { 58 | const globalStorage = useMMKV() 59 | const userStorage = useMMKV({ id: `${userId}.storage` }) 60 | 61 | const [username, setUsername] = useMMKVString("user.name", userStorage) 62 | } 63 | ``` 64 | 65 | ## Listen to value changes 66 | 67 | ```tsx 68 | function App() { 69 | useMMKVListener((key) => { 70 | console.log(`Value for "${key}" changed!`) 71 | }) 72 | } 73 | ``` 74 | 75 | ## Listen to value changes on a specific instance 76 | 77 | ```tsx 78 | function App() { 79 | const storage = useMMKV({ id: `${userId}.storage` }) 80 | 81 | useMMKVListener((key) => { 82 | console.log(`Value for "${key}" changed in user storage!`) 83 | }, storage) 84 | } 85 | ``` 86 | -------------------------------------------------------------------------------- /docs/LISTENERS.md: -------------------------------------------------------------------------------- 1 | # Listeners 2 | 3 | MMKV instances also contain an observer/listener registry. 4 | 5 | ### Add a listener when a `key`'s `value` changes. 6 | 7 | ```ts 8 | const storage = new MMKV() 9 | 10 | const listener = storage.addOnValueChangedListener((changedKey) => { 11 | const newValue = storage.getString(changedKey) 12 | console.log(`"${changedKey}" new value: ${newValue}`) 13 | }) 14 | ``` 15 | 16 | Don't forget to remove the listener when no longer needed. For example, when the user logs out: 17 | 18 | ```ts 19 | function SettingsScreen() { 20 | // ... 21 | 22 | const onLogout = useCallback(() => { 23 | // ... 24 | listener.remove() 25 | }, []) 26 | 27 | // ... 28 | } 29 | ``` 30 | -------------------------------------------------------------------------------- /docs/MIGRATE_FROM_ASYNC_STORAGE.md: -------------------------------------------------------------------------------- 1 | # Migrate from AsyncStorage 2 | 3 | Here's a migration script to copy all values from AsyncStorage to MMKV, and delete them from AsyncStorage afterwards. 4 | 5 | 6 | 7 | 8 | 9 | 10 | 60 | 61 |
storage.ts
11 | 12 | ```ts 13 | import AsyncStorage from '@react-native-async-storage/async-storage'; 14 | import {MMKV} from 'react-native-mmkv'; 15 | 16 | export const storage = new MMKV(); 17 | 18 | // TODO: Remove `hasMigratedFromAsyncStorage` after a while (when everyone has migrated) 19 | export const hasMigratedFromAsyncStorage = storage.getBoolean( 20 | 'hasMigratedFromAsyncStorage', 21 | ); 22 | 23 | // TODO: Remove `hasMigratedFromAsyncStorage` after a while (when everyone has migrated) 24 | export async function migrateFromAsyncStorage(): Promise { 25 | console.log('Migrating from AsyncStorage -> MMKV...'); 26 | const start = global.performance.now(); 27 | 28 | const keys = await AsyncStorage.getAllKeys(); 29 | 30 | for (const key of keys) { 31 | try { 32 | const value = await AsyncStorage.getItem(key); 33 | 34 | if (value != null) { 35 | if (['true', 'false'].includes(value)) { 36 | storage.set(key, value === 'true'); 37 | } else { 38 | storage.set(key, value); 39 | } 40 | 41 | AsyncStorage.removeItem(key); 42 | } 43 | } catch (error) { 44 | console.error( 45 | `Failed to migrate key "${key}" from AsyncStorage to MMKV!`, 46 | error, 47 | ); 48 | throw error; 49 | } 50 | } 51 | 52 | storage.set('hasMigratedFromAsyncStorage', true); 53 | 54 | const end = global.performance.now(); 55 | console.log(`Migrated from AsyncStorage -> MMKV in ${end - start}ms!`); 56 | } 57 | ``` 58 | 59 |
62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 113 | 114 |
App.tsx
72 | 73 | ```tsx 74 | ... 75 | import { hasMigratedFromAsyncStorage, migrateFromAsyncStorage } from './storage'; 76 | ... 77 | 78 | export default function App() { 79 | // TODO: Remove `hasMigratedFromAsyncStorage` after a while (when everyone has migrated) 80 | const [hasMigrated, setHasMigrated] = useState(hasMigratedFromAsyncStorage); 81 | 82 | ... 83 | 84 | useEffect(() => { 85 | if (!hasMigratedFromAsyncStorage) { 86 | InteractionManager.runAfterInteractions(async () => { 87 | try { 88 | await migrateFromAsyncStorage() 89 | setHasMigrated(true) 90 | } catch (e) { 91 | // TODO: fall back to AsyncStorage? Wipe storage clean and use MMKV? Crash app? 92 | } 93 | }); 94 | } 95 | }, []); 96 | 97 | if (!hasMigrated) { 98 | // show loading indicator while app is migrating storage... 99 | return ( 100 | 101 | 102 | 103 | ); 104 | } 105 | 106 | return ( 107 | 108 | ); 109 | } 110 | ``` 111 | 112 |
115 | -------------------------------------------------------------------------------- /docs/WRAPPER_JOTAI.md: -------------------------------------------------------------------------------- 1 | # jotai wrapper 2 | 3 | If you want to use MMKV with [Jotai](https://github.com/pmndrs/jotai), create the following `atomWithMMKV` function: 4 | 5 | ```ts 6 | import { atomWithStorage, createJSONStorage } from 'jotai/utils'; 7 | import { MMKV } from 'react-native-mmkv'; 8 | 9 | const storage = new MMKV(); 10 | 11 | function getItem(key: string): string | null { 12 | const value = storage.getString(key) 13 | return value ? value : null 14 | } 15 | 16 | function setItem(key: string, value: string): void { 17 | storage.set(key, value) 18 | } 19 | 20 | function removeItem(key: string): void { 21 | storage.delete(key); 22 | } 23 | 24 | function subscribe( 25 | key: string, 26 | callback: (value: string | null) => void 27 | ): () => void { 28 | const listener = (changedKey: string) => { 29 | if (changedKey === key) { 30 | callback(getItem(key)) 31 | } 32 | } 33 | 34 | const { remove } = storage.addOnValueChangedListener(listener) 35 | 36 | return () => { 37 | remove() 38 | } 39 | } 40 | 41 | export const atomWithMMKV = (key: string, initialValue: T) => 42 | atomWithStorage( 43 | key, 44 | initialValue, 45 | createJSONStorage(() => ({ 46 | getItem, 47 | setItem, 48 | removeItem, 49 | subscribe, 50 | })), 51 | { getOnInit: true } 52 | ); 53 | ``` 54 | 55 | Then simply use `atomWithMMKV(..)` instead of `atom(..)` when creating an atom you'd like to persist accross app starts. 56 | 57 | ```ts 58 | const myAtom = atomWithMMKV('my-atom-key', 'value'); 59 | ``` 60 | 61 | *Note:* `createJSONStorage` handles `JSON.stringify()`/`JSON.parse()` when setting and returning the stored value. 62 | 63 | See the official Jotai doc here: https://jotai.org/docs/utils/atom-with-storage 64 | -------------------------------------------------------------------------------- /docs/WRAPPER_MOBX.md: -------------------------------------------------------------------------------- 1 | # mobx-persist-store wrapper 2 | 3 | If you want to use MMKV with [mobx-persist-store](https://github.com/quarrant/mobx-persist-store), create the following `storage` object: 4 | 5 | ```ts 6 | import { configurePersistable } from 'mobx-persist-store' 7 | import { MMKV } from "react-native-mmkv" 8 | 9 | const storage = new MMKV() 10 | 11 | configurePersistable({ 12 | storage: { 13 | setItem: (key, data) => storage.set(key, data), 14 | getItem: (key) => storage.getString(key), 15 | removeItem: (key) => storage.delete(key), 16 | }, 17 | }) 18 | ``` 19 | -------------------------------------------------------------------------------- /docs/WRAPPER_MOBXPERSIST.md: -------------------------------------------------------------------------------- 1 | # mobx-persist wrapper 2 | 3 | If you want to use MMKV with [mobx-persist](https://github.com/pinqy520/mobx-persist), create the following `hydrate` function: 4 | 5 | ```ts 6 | import { create } from "mobx-persist" 7 | import { MMKV } from "react-native-mmkv" 8 | 9 | const storage = new MMKV() 10 | 11 | const mmkvStorage = { 12 | clear: () => { 13 | storage.clearAll() 14 | return Promise.resolve() 15 | }, 16 | setItem: (key, value) => { 17 | storage.set(key, value) 18 | return Promise.resolve(true) 19 | }, 20 | getItem: (key) => { 21 | const value = storage.getString(key) 22 | return Promise.resolve(value) 23 | }, 24 | removeItem: (key) => { 25 | storage.delete(key) 26 | return Promise.resolve() 27 | }, 28 | } 29 | 30 | const hydrate = create({ 31 | storage: mmkvStorage, 32 | jsonify: true, 33 | }) 34 | 35 | ``` 36 | 37 | You can see a full working example [here](https://github.com/riamon-v/rn-mmkv-with-mobxpersist) 38 | -------------------------------------------------------------------------------- /docs/WRAPPER_REACT_QUERY.md: -------------------------------------------------------------------------------- 1 | # react-query wrapper 2 | 3 | If you want to use MMKV with [react-query](https://tanstack.com/query/latest/docs/framework/react/overview), follow further steps: 4 | 5 | 1. Install `react-query` persist packages 6 | 7 | ```sh 8 | yarn add @tanstack/query-sync-storage-persister @tanstack/react-query-persist-client 9 | ``` 10 | 11 | 2. Add next code into your app 12 | 13 | ```ts 14 | import { createSyncStoragePersister } from '@tanstack/query-sync-storage-persister' 15 | import { MMKV } from "react-native-mmkv" 16 | 17 | const storage = new MMKV(); 18 | 19 | const clientStorage = { 20 | setItem: (key, value) => { 21 | storage.set(key, value); 22 | }, 23 | getItem: (key) => { 24 | const value = storage.getString(key); 25 | return value === undefined ? null : value; 26 | }, 27 | removeItem: (key) => { 28 | storage.delete(key); 29 | }, 30 | }; 31 | 32 | export const clientPersister = createSyncStoragePersister({ storage: clientStorage }); 33 | ``` 34 | 35 | 3. Use created `clientPersister` in your root component (eg. `App.tsx`) 36 | 37 | ```tsx 38 | import { PersistQueryClientProvider } from '@tanstack/react-query-persist-client' 39 | 40 | const App = () => { 41 | return ( 42 | 43 | {...} 44 | 45 | ); 46 | }; 47 | ``` 48 | 49 | For more information check their official [docs](https://tanstack.com/query/latest/docs/framework/react/plugins/persistQueryClient#persistqueryclientprovider) 50 | -------------------------------------------------------------------------------- /docs/WRAPPER_RECOIL.md: -------------------------------------------------------------------------------- 1 | # recoil storage wrapper 2 | 3 | If you want to use MMKV with [recoil](https://recoiljs.org/), Use the following persist code: 4 | 5 | ```tsx 6 | const persistAtom = (key) => ({ setSelf, onSet }) => { 7 | setSelf(() => { 8 | let data = storage.getString(key); 9 | if (data != null){ 10 | return JSON.parse(data); 11 | } else { 12 | return new DefaultValue(); 13 | } 14 | }); 15 | 16 | onSet((newValue, _, isReset) => { 17 | if (isReset) { 18 | storage.delete(key); 19 | } else { 20 | storage.set(key, JSON.stringify(newValue)); 21 | } 22 | }); 23 | }; 24 | ``` 25 | -------------------------------------------------------------------------------- /docs/WRAPPER_REDUX.md: -------------------------------------------------------------------------------- 1 | # redux-persist storage wrapper 2 | 3 | If you want to use MMKV with [redux-persist](https://github.com/rt2zz/redux-persist), create the following `storage` object: 4 | 5 | ```ts 6 | import { Storage } from 'redux-persist' 7 | import { MMKV } from "react-native-mmkv" 8 | 9 | const storage = new MMKV() 10 | 11 | export const reduxStorage: Storage = { 12 | setItem: (key, value) => { 13 | storage.set(key, value) 14 | return Promise.resolve(true) 15 | }, 16 | getItem: (key) => { 17 | const value = storage.getString(key) 18 | return Promise.resolve(value) 19 | }, 20 | removeItem: (key) => { 21 | storage.delete(key) 22 | return Promise.resolve() 23 | }, 24 | } 25 | ``` 26 | -------------------------------------------------------------------------------- /docs/WRAPPER_ZUSTAND_PERSIST_MIDDLEWARE.md: -------------------------------------------------------------------------------- 1 | # zustand persist-middleware wrapper 2 | 3 | If you want to use MMKV with [zustand persist-middleware](https://github.com/pmndrs/zustand#persist-middleware), create the following `storage` object: 4 | 5 | ```ts 6 | import { StateStorage } from 'zustand/middleware' 7 | import { MMKV } from 'react-native-mmkv' 8 | 9 | const storage = new MMKV() 10 | 11 | const zustandStorage: StateStorage = { 12 | setItem: (name, value) => { 13 | return storage.set(name, value) 14 | }, 15 | getItem: (name) => { 16 | const value = storage.getString(name) 17 | return value ?? null 18 | }, 19 | removeItem: (name) => { 20 | return storage.delete(name) 21 | }, 22 | } 23 | ``` 24 | -------------------------------------------------------------------------------- /package/.clang-format: -------------------------------------------------------------------------------- 1 | # Config for clang-format version 16 2 | 3 | # Standard 4 | BasedOnStyle: llvm 5 | Standard: c++14 6 | 7 | # Indentation 8 | IndentWidth: 2 9 | ColumnLimit: 100 10 | 11 | # Includes 12 | SortIncludes: true 13 | SortUsingDeclarations: true 14 | 15 | # Pointer and reference alignment 16 | PointerAlignment: Left 17 | ReferenceAlignment: Left 18 | ReflowComments: true 19 | 20 | # Line breaking options 21 | BreakBeforeBraces: Attach 22 | BreakConstructorInitializers: BeforeColon 23 | AllowShortFunctionsOnASingleLine: Empty 24 | IndentCaseLabels: true 25 | NamespaceIndentation: Inner 26 | 27 | -------------------------------------------------------------------------------- /package/.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | root: true, 3 | extends: ['@react-native', 'plugin:prettier/recommended'], 4 | plugins: ['prettier'], 5 | ignorePatterns: ['scripts', 'lib'], 6 | rules: { 7 | 'prettier/prettier': ['warn'], 8 | }, 9 | }; 10 | -------------------------------------------------------------------------------- /package/.gitattributes: -------------------------------------------------------------------------------- 1 | *.pbxproj -text 2 | # specific for windows script files 3 | *.bat text eol=crlf 4 | # All Headers are C++ 5 | **/*.h linguist-language=C++ 6 | -------------------------------------------------------------------------------- /package/.gitignore: -------------------------------------------------------------------------------- 1 | # OSX 2 | # 3 | .DS_Store 4 | 5 | # XDE 6 | .expo/ 7 | 8 | # VSCode 9 | .vscode/ 10 | jsconfig.json 11 | 12 | # Xcode 13 | # 14 | build/ 15 | *.pbxuser 16 | !default.pbxuser 17 | *.mode1v3 18 | !default.mode1v3 19 | *.mode2v3 20 | !default.mode2v3 21 | *.perspectivev3 22 | !default.perspectivev3 23 | xcuserdata 24 | *.xccheckout 25 | *.moved-aside 26 | DerivedData 27 | *.hmap 28 | *.ipa 29 | *.xcuserstate 30 | project.xcworkspace 31 | 32 | # Android/IJ 33 | # 34 | .classpath 35 | .cxx 36 | .gradle 37 | .idea 38 | .project 39 | .settings 40 | local.properties 41 | android.iml 42 | 43 | # Cocoapods 44 | # 45 | example/ios/Pods 46 | 47 | # Ruby 48 | example/vendor/ 49 | 50 | # node.js 51 | # 52 | node_modules/ 53 | npm-debug.log 54 | 55 | # BUCK 56 | buck-out/ 57 | \.buckd/ 58 | android/app/libs 59 | android/keystores/debug.keystore 60 | 61 | # Expo 62 | .expo/ 63 | 64 | # Turborepo 65 | .turbo/ 66 | 67 | # generated by bob 68 | lib/ 69 | -------------------------------------------------------------------------------- /package/.nvmrc: -------------------------------------------------------------------------------- 1 | v18 2 | -------------------------------------------------------------------------------- /package/.prettierrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | bracketSpacing: true, 3 | bracketSameLine: true, 4 | singleQuote: true, 5 | trailingComma: 'all', 6 | semi: false, 7 | tabWidth: 2, 8 | useTabs: false, 9 | printWidth: 140 10 | } 11 | -------------------------------------------------------------------------------- /package/.watchmanconfig: -------------------------------------------------------------------------------- 1 | {} -------------------------------------------------------------------------------- /package/README.md: -------------------------------------------------------------------------------- 1 | # react-native-mmkv 2 | 3 | The fastest key/value storage for React Native. ~30x faster than AsyncStorage! 4 | 5 | See [README.md](https://github.com/mrousavy/react-native-mmkv) for more information. 6 | -------------------------------------------------------------------------------- /package/android/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.9.0) 2 | project(ReactNativeMmkv) 3 | 4 | set(CMAKE_VERBOSE_MAKEFILE ON) 5 | set(CMAKE_CXX_STANDARD 17) 6 | 7 | # Compile sources 8 | add_library( 9 | react-native-mmkv 10 | SHARED 11 | src/main/cpp/AndroidLogger.cpp 12 | ../cpp/MmkvHostObject.cpp 13 | ../cpp/NativeMmkvModule.cpp 14 | ) 15 | 16 | # Add headers search paths 17 | target_include_directories(react-native-mmkv PUBLIC ../MMKV/Core) 18 | target_include_directories(react-native-mmkv PUBLIC ../cpp) 19 | 20 | # Add MMKV core dependency 21 | add_subdirectory(../MMKV/Core core) 22 | 23 | # Add android/log dependency 24 | find_library(log-lib log) 25 | 26 | target_link_libraries( 27 | react-native-mmkv 28 | core # <-- MMKV core 29 | ${log-lib} # <-- Logcat logger 30 | android # <-- Android JNI core 31 | react_codegen_RNMmkvSpec # <-- Generated Specs from CodeGen 32 | ) 33 | -------------------------------------------------------------------------------- /package/android/build.gradle: -------------------------------------------------------------------------------- 1 | buildscript { 2 | repositories { 3 | google() 4 | mavenCentral() 5 | } 6 | 7 | dependencies { 8 | classpath "com.android.tools.build:gradle:7.2.1" 9 | } 10 | } 11 | 12 | def isNewArchitectureEnabled() { 13 | return rootProject.hasProperty("newArchEnabled") && rootProject.getProperty("newArchEnabled") == "true" 14 | } 15 | 16 | apply plugin: "com.android.library" 17 | 18 | if (isNewArchitectureEnabled()) { 19 | apply plugin: "com.facebook.react" 20 | } 21 | 22 | def getExtOrDefault(name) { 23 | return rootProject.ext.has(name) ? rootProject.ext.get(name) : project.properties["Mmkv_" + name] 24 | } 25 | 26 | def getExtOrIntegerDefault(name) { 27 | return rootProject.ext.has(name) ? rootProject.ext.get(name) : (project.properties["Mmkv_" + name]).toInteger() 28 | } 29 | 30 | logger.warn("[react-native-mmkv] Thank you for using react-native-mmkv ❤️") 31 | logger.warn("[react-native-mmkv] If you enjoy using react-native-mmkv, please consider sponsoring this project: https://github.com/sponsors/mrousavy") 32 | 33 | android { 34 | namespace "com.mrousavy.mmkv" 35 | 36 | ndkVersion getExtOrDefault("ndkVersion") 37 | compileSdkVersion getExtOrIntegerDefault("compileSdkVersion") 38 | 39 | defaultConfig { 40 | minSdkVersion getExtOrIntegerDefault("minSdkVersion") 41 | targetSdkVersion getExtOrIntegerDefault("targetSdkVersion") 42 | buildConfigField "boolean", "IS_NEW_ARCHITECTURE_ENABLED", isNewArchitectureEnabled().toString() 43 | } 44 | 45 | buildFeatures { 46 | buildConfig true 47 | } 48 | 49 | buildTypes { 50 | release { 51 | minifyEnabled false 52 | } 53 | } 54 | 55 | lintOptions { 56 | disable "GradleCompatible" 57 | } 58 | 59 | compileOptions { 60 | sourceCompatibility JavaVersion.VERSION_1_8 61 | targetCompatibility JavaVersion.VERSION_1_8 62 | } 63 | 64 | sourceSets { 65 | main { 66 | if (isNewArchitectureEnabled()) { 67 | java.srcDirs += [ 68 | // This is needed to build Kotlin project with NewArch enabled 69 | "${project.buildDir}/generated/source/codegen/java" 70 | ] 71 | } 72 | } 73 | } 74 | } 75 | 76 | repositories { 77 | mavenCentral() 78 | google() 79 | } 80 | 81 | 82 | dependencies { 83 | // For < 0.71, this will be from the local maven repo 84 | // For > 0.71, this will be replaced by `com.facebook.react:react-android:$version` by react gradle plugin 85 | //noinspection GradleDynamicVersion 86 | implementation "com.facebook.react:react-native:+" 87 | } 88 | 89 | if (isNewArchitectureEnabled()) { 90 | react { 91 | jsRootDir = file("../src/") 92 | libraryName = "Mmkv" 93 | codegenJavaPackageName = "com.mrousavy.mmkv" 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /package/android/gradle.properties: -------------------------------------------------------------------------------- 1 | Mmkv_kotlinVersion=1.9.24 2 | Mmkv_minSdkVersion=23 3 | Mmkv_targetSdkVersion=34 4 | Mmkv_compileSdkVersion=34 5 | Mmkv_ndkversion=26.1.10909125 6 | -------------------------------------------------------------------------------- /package/android/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /package/android/src/main/cpp/AndroidLogger.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // AndroidMmkvLogger.cpp 3 | // react-native-mmkv 4 | // 5 | // Created by Marc Rousavy on 05.03.24. 6 | // 7 | 8 | #include "MmkvLogger.h" 9 | #include 10 | 11 | void MmkvLogger::log(const std::string& tag, const std::string& message) { 12 | #pragma clang diagnostic push 13 | #pragma clang diagnostic ignored "-Wformat-security" 14 | __android_log_print(ANDROID_LOG_INFO, tag.c_str(), message.c_str()); 15 | #pragma clang diagnostic pop 16 | } 17 | -------------------------------------------------------------------------------- /package/android/src/main/java/com/mrousavy/mmkv/MmkvPackage.java: -------------------------------------------------------------------------------- 1 | package com.mrousavy.mmkv; 2 | 3 | import androidx.annotation.NonNull; 4 | import androidx.annotation.Nullable; 5 | 6 | import com.facebook.react.bridge.NativeModule; 7 | import com.facebook.react.bridge.ReactApplicationContext; 8 | import com.facebook.react.module.model.ReactModuleInfo; 9 | import com.facebook.react.module.model.ReactModuleInfoProvider; 10 | import com.facebook.react.TurboReactPackage; 11 | 12 | import java.util.HashMap; 13 | import java.util.Map; 14 | 15 | public class MmkvPackage extends TurboReactPackage { 16 | @Nullable 17 | @Override 18 | public NativeModule getModule(String name, @NonNull ReactApplicationContext reactContext) { 19 | if (name.equals(MmkvPlatformContextModule.NAME)) { 20 | return new MmkvPlatformContextModule(reactContext); 21 | } else { 22 | return null; 23 | } 24 | } 25 | 26 | @Override 27 | public ReactModuleInfoProvider getReactModuleInfoProvider() { 28 | return () -> { 29 | final Map moduleInfos = new HashMap<>(); 30 | moduleInfos.put( 31 | MmkvPlatformContextModule.NAME, 32 | new ReactModuleInfo( 33 | MmkvPlatformContextModule.NAME, 34 | MmkvPlatformContextModule.NAME, 35 | false, // canOverrideExistingModule 36 | false, // needsEagerInit 37 | true, // hasConstants 38 | false, // isCxxModule 39 | true // isTurboModule 40 | )); 41 | return moduleInfos; 42 | }; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /package/android/src/main/java/com/mrousavy/mmkv/MmkvPlatformContextModule.java: -------------------------------------------------------------------------------- 1 | package com.mrousavy.mmkv; 2 | 3 | import androidx.annotation.Nullable; 4 | 5 | import com.facebook.react.bridge.ReactApplicationContext; 6 | 7 | public class MmkvPlatformContextModule extends NativeMmkvPlatformContextSpec { 8 | private final ReactApplicationContext context; 9 | 10 | public MmkvPlatformContextModule(ReactApplicationContext reactContext) { 11 | super(reactContext); 12 | context = reactContext; 13 | } 14 | 15 | @Override 16 | public String getBaseDirectory() { 17 | return context.getFilesDir().getAbsolutePath() + "/mmkv"; 18 | } 19 | 20 | @Nullable 21 | @Override 22 | public String getAppGroupDirectory() { 23 | // AppGroups do not exist on Android. It's iOS only. 24 | return null; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /package/babel.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | presets: ['module:@react-native/babel-preset'], 3 | }; 4 | -------------------------------------------------------------------------------- /package/cpp/MMKVManagedBuffer.h: -------------------------------------------------------------------------------- 1 | // 2 | // ManagedBuffer.h 3 | // react-native-mmkv 4 | // 5 | // Created by Marc Rousavy on 25.03.24. 6 | // 7 | 8 | #pragma once 9 | 10 | #include "MMKVManagedBuffer.h" 11 | #include 12 | 13 | using namespace facebook; 14 | 15 | /** 16 | A jsi::MutableBuffer that manages mmkv::MMBuffer memory (by ownership). 17 | */ 18 | class MMKVManagedBuffer : public jsi::MutableBuffer { 19 | public: 20 | explicit MMKVManagedBuffer(mmkv::MMBuffer&& buffer) : _buffer(std::move(buffer)) {} 21 | 22 | uint8_t* data() override { 23 | return static_cast(_buffer.getPtr()); 24 | } 25 | 26 | size_t size() const override { 27 | return _buffer.length(); 28 | } 29 | 30 | private: 31 | mmkv::MMBuffer _buffer; 32 | }; 33 | -------------------------------------------------------------------------------- /package/cpp/MmkvHostObject.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // MmkvHostObject.cpp 3 | // Mmkv 4 | // 5 | // Created by Marc Rousavy on 03.09.21. 6 | // Copyright © 2021 Facebook. All rights reserved. 7 | // 8 | 9 | #include "MmkvHostObject.h" 10 | #include "MMKVManagedBuffer.h" 11 | #include "MmkvLogger.h" 12 | #include 13 | #include 14 | #include 15 | 16 | using namespace mmkv; 17 | using namespace facebook; 18 | 19 | MmkvHostObject::MmkvHostObject(const facebook::react::MMKVConfig& config) { 20 | std::string path = config.path.has_value() ? config.path.value() : ""; 21 | std::string encryptionKey = config.encryptionKey.has_value() ? config.encryptionKey.value() : ""; 22 | bool hasEncryptionKey = encryptionKey.size() > 0; 23 | MmkvLogger::log("RNMMKV", "Creating MMKV instance \"%s\"... (Path: %s, Encrypted: %s)", 24 | config.id.c_str(), path.c_str(), hasEncryptionKey ? "true" : "false"); 25 | 26 | std::string* pathPtr = path.size() > 0 ? &path : nullptr; 27 | std::string* encryptionKeyPtr = encryptionKey.size() > 0 ? &encryptionKey : nullptr; 28 | MMKVMode mode = getMMKVMode(config); 29 | if (config.readOnly.has_value() && config.readOnly.value()) { 30 | MmkvLogger::log("RNMMKV", "Instance is read-only!"); 31 | mode = mode | MMKVMode::MMKV_READ_ONLY; 32 | } 33 | 34 | #ifdef __APPLE__ 35 | instance = MMKV::mmkvWithID(config.id, mode, encryptionKeyPtr, pathPtr); 36 | #else 37 | instance = MMKV::mmkvWithID(config.id, DEFAULT_MMAP_SIZE, mode, encryptionKeyPtr, pathPtr); 38 | #endif 39 | 40 | if (instance == nullptr) [[unlikely]] { 41 | // Check if instanceId is invalid 42 | if (config.id.empty()) [[unlikely]] { 43 | throw std::runtime_error("Failed to create MMKV instance! `id` cannot be empty!"); 44 | } 45 | 46 | // Check if encryptionKey is invalid 47 | if (encryptionKey.size() > 16) [[unlikely]] { 48 | throw std::runtime_error( 49 | "Failed to create MMKV instance! `encryptionKey` cannot be longer than 16 bytes!"); 50 | } 51 | 52 | throw std::runtime_error("Failed to create MMKV instance!"); 53 | } 54 | } 55 | 56 | MmkvHostObject::~MmkvHostObject() { 57 | if (instance != nullptr) { 58 | std::string instanceId = instance->mmapID(); 59 | MmkvLogger::log("RNMMKV", "Destroying MMKV instance \"%s\"...", instanceId.c_str()); 60 | instance->sync(); 61 | instance->clearMemoryCache(); 62 | } 63 | instance = nullptr; 64 | } 65 | 66 | std::vector MmkvHostObject::getPropertyNames(jsi::Runtime& rt) { 67 | return jsi::PropNameID::names(rt, "set", "getBoolean", "getBuffer", "getString", "getNumber", 68 | "contains", "delete", "getAllKeys", "deleteAll", "recrypt", "trim", 69 | "size", "isReadOnly"); 70 | } 71 | 72 | MMKVMode MmkvHostObject::getMMKVMode(const facebook::react::MMKVConfig& config) { 73 | if (!config.mode.has_value()) { 74 | return MMKVMode::MMKV_SINGLE_PROCESS; 75 | } 76 | react::NativeMmkvMode mode = config.mode.value(); 77 | switch (mode) { 78 | case react::NativeMmkvMode::SINGLE_PROCESS: 79 | return MMKVMode::MMKV_SINGLE_PROCESS; 80 | case react::NativeMmkvMode::MULTI_PROCESS: 81 | return MMKVMode::MMKV_MULTI_PROCESS; 82 | default: 83 | [[unlikely]] throw std::runtime_error("Invalid MMKV Mode value!"); 84 | } 85 | } 86 | 87 | jsi::Value MmkvHostObject::get(jsi::Runtime& runtime, const jsi::PropNameID& propNameId) { 88 | std::string propName = propNameId.utf8(runtime); 89 | 90 | if (propName == "set") { 91 | // MMKV.set(key: string, value: string | number | bool | ArrayBuffer) 92 | return jsi::Function::createFromHostFunction( 93 | runtime, jsi::PropNameID::forAscii(runtime, propName), 94 | 2, // key, value 95 | [this](jsi::Runtime& runtime, const jsi::Value& thisValue, const jsi::Value* arguments, 96 | size_t count) -> jsi::Value { 97 | if (count != 2 || !arguments[0].isString()) [[unlikely]] { 98 | throw jsi::JSError(runtime, 99 | "MMKV::set: First argument ('key') has to be of type string!"); 100 | } 101 | 102 | std::string keyName = arguments[0].getString(runtime).utf8(runtime); 103 | 104 | bool successful = false; 105 | if (arguments[1].isBool()) { 106 | // bool 107 | successful = instance->set(arguments[1].getBool(), keyName); 108 | } else if (arguments[1].isNumber()) { 109 | // number 110 | successful = instance->set(arguments[1].getNumber(), keyName); 111 | } else if (arguments[1].isString()) { 112 | // string 113 | std::string stringValue = arguments[1].getString(runtime).utf8(runtime); 114 | successful = instance->set(stringValue, keyName); 115 | } else if (arguments[1].isObject()) { 116 | // object 117 | jsi::Object object = arguments[1].getObject(runtime); 118 | if (object.isArrayBuffer(runtime)) { 119 | // ArrayBuffer 120 | jsi::ArrayBuffer arrayBuffer = object.getArrayBuffer(runtime); 121 | MMBuffer data(arrayBuffer.data(runtime), arrayBuffer.size(runtime), MMBufferNoCopy); 122 | successful = instance->set(data, keyName); 123 | } else [[unlikely]] { 124 | // unknown object 125 | throw jsi::JSError( 126 | runtime, 127 | "MMKV::set: 'value' argument is an object, but not of type ArrayBuffer!"); 128 | } 129 | } else [[unlikely]] { 130 | // unknown type 131 | throw jsi::JSError( 132 | runtime, 133 | "MMKV::set: 'value' argument is not of type bool, number, string or buffer!"); 134 | } 135 | 136 | if (!successful) [[unlikely]] { 137 | if (instance->isReadOnly()) { 138 | throw jsi::JSError(runtime, 139 | "Failed to set " + keyName + "! This instance is read-only!"); 140 | } else { 141 | throw jsi::JSError(runtime, "Failed to set " + keyName + "!"); 142 | } 143 | } 144 | 145 | return jsi::Value::undefined(); 146 | }); 147 | } 148 | 149 | if (propName == "getBoolean") { 150 | // MMKV.getBoolean(key: string) 151 | return jsi::Function::createFromHostFunction( 152 | runtime, jsi::PropNameID::forAscii(runtime, propName), 153 | 1, // key 154 | [this](jsi::Runtime& runtime, const jsi::Value& thisValue, const jsi::Value* arguments, 155 | size_t count) -> jsi::Value { 156 | if (count != 1 || !arguments[0].isString()) [[unlikely]] { 157 | throw jsi::JSError(runtime, "First argument ('key') has to be of type string!"); 158 | } 159 | 160 | std::string keyName = arguments[0].getString(runtime).utf8(runtime); 161 | bool hasValue; 162 | bool value = instance->getBool(keyName, false, &hasValue); 163 | if (!hasValue) [[unlikely]] { 164 | return jsi::Value::undefined(); 165 | } 166 | return jsi::Value(value); 167 | }); 168 | } 169 | 170 | if (propName == "getNumber") { 171 | // MMKV.getNumber(key: string) 172 | return jsi::Function::createFromHostFunction( 173 | runtime, jsi::PropNameID::forAscii(runtime, propName), 174 | 1, // key 175 | [this](jsi::Runtime& runtime, const jsi::Value& thisValue, const jsi::Value* arguments, 176 | size_t count) -> jsi::Value { 177 | if (count != 1 || !arguments[0].isString()) [[unlikely]] { 178 | throw jsi::JSError(runtime, "First argument ('key') has to be of type string!"); 179 | } 180 | 181 | std::string keyName = arguments[0].getString(runtime).utf8(runtime); 182 | bool hasValue; 183 | double value = instance->getDouble(keyName, 0.0, &hasValue); 184 | if (!hasValue) [[unlikely]] { 185 | return jsi::Value::undefined(); 186 | } 187 | return jsi::Value(value); 188 | }); 189 | } 190 | 191 | if (propName == "getString") { 192 | // MMKV.getString(key: string) 193 | return jsi::Function::createFromHostFunction( 194 | runtime, jsi::PropNameID::forAscii(runtime, propName), 195 | 1, // key 196 | [this](jsi::Runtime& runtime, const jsi::Value& thisValue, const jsi::Value* arguments, 197 | size_t count) -> jsi::Value { 198 | if (count != 1 || !arguments[0].isString()) [[unlikely]] { 199 | throw jsi::JSError(runtime, "First argument ('key') has to be of type string!"); 200 | } 201 | 202 | std::string keyName = arguments[0].getString(runtime).utf8(runtime); 203 | std::string result; 204 | bool hasValue = instance->getString(keyName, result); 205 | if (!hasValue) [[unlikely]] { 206 | return jsi::Value::undefined(); 207 | } 208 | return jsi::Value(runtime, jsi::String::createFromUtf8(runtime, result)); 209 | }); 210 | } 211 | 212 | if (propName == "getBuffer") { 213 | // MMKV.getBuffer(key: string) 214 | return jsi::Function::createFromHostFunction( 215 | runtime, jsi::PropNameID::forAscii(runtime, propName), 216 | 1, // key 217 | [this](jsi::Runtime& runtime, const jsi::Value& thisValue, const jsi::Value* arguments, 218 | size_t count) -> jsi::Value { 219 | if (count != 1 || !arguments[0].isString()) [[unlikely]] { 220 | throw jsi::JSError(runtime, "First argument ('key') has to be of type string!"); 221 | } 222 | 223 | std::string keyName = arguments[0].getString(runtime).utf8(runtime); 224 | mmkv::MMBuffer buffer; 225 | bool hasValue = instance->getBytes(keyName, buffer); 226 | if (!hasValue) [[unlikely]] { 227 | return jsi::Value::undefined(); 228 | } 229 | auto mutableData = std::make_shared(std::move(buffer)); 230 | return jsi::ArrayBuffer(runtime, mutableData); 231 | }); 232 | } 233 | 234 | if (propName == "contains") { 235 | // MMKV.contains(key: string) 236 | return jsi::Function::createFromHostFunction( 237 | runtime, jsi::PropNameID::forAscii(runtime, propName), 238 | 1, // key 239 | [this](jsi::Runtime& runtime, const jsi::Value& thisValue, const jsi::Value* arguments, 240 | size_t count) -> jsi::Value { 241 | if (count != 1 || !arguments[0].isString()) [[unlikely]] { 242 | throw jsi::JSError(runtime, "First argument ('key') has to be of type string!"); 243 | } 244 | 245 | std::string keyName = arguments[0].getString(runtime).utf8(runtime); 246 | bool containsKey = instance->containsKey(keyName); 247 | return jsi::Value(containsKey); 248 | }); 249 | } 250 | 251 | if (propName == "delete") { 252 | // MMKV.delete(key: string) 253 | return jsi::Function::createFromHostFunction( 254 | runtime, jsi::PropNameID::forAscii(runtime, propName), 255 | 1, // key 256 | [this](jsi::Runtime& runtime, const jsi::Value& thisValue, const jsi::Value* arguments, 257 | size_t count) -> jsi::Value { 258 | if (count != 1 || !arguments[0].isString()) [[unlikely]] { 259 | throw jsi::JSError(runtime, "First argument ('key') has to be of type string!"); 260 | } 261 | 262 | std::string keyName = arguments[0].getString(runtime).utf8(runtime); 263 | instance->removeValueForKey(keyName); 264 | return jsi::Value::undefined(); 265 | }); 266 | } 267 | 268 | if (propName == "getAllKeys") { 269 | // MMKV.getAllKeys() 270 | return jsi::Function::createFromHostFunction( 271 | runtime, jsi::PropNameID::forAscii(runtime, propName), 0, 272 | [this](jsi::Runtime& runtime, const jsi::Value& thisValue, const jsi::Value* arguments, 273 | size_t count) -> jsi::Value { 274 | std::vector keys = instance->allKeys(); 275 | jsi::Array array(runtime, keys.size()); 276 | for (int i = 0; i < keys.size(); i++) { 277 | array.setValueAtIndex(runtime, i, keys[i]); 278 | } 279 | return array; 280 | }); 281 | } 282 | 283 | if (propName == "clearAll") { 284 | // MMKV.clearAll() 285 | return jsi::Function::createFromHostFunction( 286 | runtime, jsi::PropNameID::forAscii(runtime, propName), 0, 287 | [this](jsi::Runtime& runtime, const jsi::Value& thisValue, const jsi::Value* arguments, 288 | size_t count) -> jsi::Value { 289 | instance->clearAll(); 290 | return jsi::Value::undefined(); 291 | }); 292 | } 293 | 294 | if (propName == "recrypt") { 295 | // MMKV.recrypt(encryptionKey) 296 | return jsi::Function::createFromHostFunction( 297 | runtime, jsi::PropNameID::forAscii(runtime, propName), 298 | 1, // encryptionKey 299 | [this](jsi::Runtime& runtime, const jsi::Value& thisValue, const jsi::Value* arguments, 300 | size_t count) -> jsi::Value { 301 | if (count != 1) [[unlikely]] { 302 | throw jsi::JSError(runtime, "Expected 1 argument (encryptionKey), but received " + 303 | std::to_string(count) + "!"); 304 | } 305 | 306 | bool successful = false; 307 | if (arguments[0].isUndefined()) { 308 | // reset encryption key to "no encryption" 309 | successful = instance->reKey(std::string()); 310 | } else if (arguments[0].isString()) { 311 | // reKey(..) with new encryption-key 312 | std::string encryptionKey = arguments[0].getString(runtime).utf8(runtime); 313 | successful = instance->reKey(encryptionKey); 314 | } else [[unlikely]] { 315 | // Invalid argument (maybe object?) 316 | throw jsi::JSError( 317 | runtime, 318 | "First argument ('encryptionKey') has to be of type string (or undefined)!"); 319 | } 320 | 321 | if (!successful) [[unlikely]] { 322 | throw jsi::JSError(runtime, "Failed to recrypt MMKV instance!"); 323 | } 324 | 325 | return jsi::Value::undefined(); 326 | }); 327 | } 328 | 329 | if (propName == "trim") { 330 | // MMKV.trim() 331 | return jsi::Function::createFromHostFunction( 332 | runtime, jsi::PropNameID::forAscii(runtime, propName), 0, 333 | [this](jsi::Runtime& runtime, const jsi::Value& thisValue, const jsi::Value* arguments, 334 | size_t count) -> jsi::Value { 335 | instance->clearMemoryCache(); 336 | instance->trim(); 337 | 338 | return jsi::Value::undefined(); 339 | }); 340 | } 341 | 342 | if (propName == "size") { 343 | // MMKV.size 344 | size_t size = instance->actualSize(); 345 | return jsi::Value(static_cast(size)); 346 | } 347 | 348 | if (propName == "isReadOnly") { 349 | // MMKV.isReadOnly 350 | bool isReadOnly = instance->isReadOnly(); 351 | return jsi::Value(isReadOnly); 352 | } 353 | 354 | return jsi::Value::undefined(); 355 | } 356 | -------------------------------------------------------------------------------- /package/cpp/MmkvHostObject.h: -------------------------------------------------------------------------------- 1 | // 2 | // MmkvHostObject.h 3 | // Mmkv 4 | // 5 | // Created by Marc Rousavy on 03.09.21. 6 | // Copyright © 2021 Facebook. All rights reserved. 7 | // 8 | 9 | #pragma once 10 | 11 | #include "MMKV.h" 12 | #include "NativeMmkvModule.h" 13 | #include 14 | 15 | using namespace facebook; 16 | using namespace mmkv; 17 | 18 | class MmkvHostObject : public jsi::HostObject { 19 | public: 20 | MmkvHostObject(const facebook::react::MMKVConfig& config); 21 | ~MmkvHostObject(); 22 | 23 | public: 24 | jsi::Value get(jsi::Runtime&, const jsi::PropNameID& name) override; 25 | std::vector getPropertyNames(jsi::Runtime& rt) override; 26 | 27 | private: 28 | static MMKVMode getMMKVMode(const facebook::react::MMKVConfig& config); 29 | 30 | private: 31 | MMKV* instance; 32 | }; 33 | -------------------------------------------------------------------------------- /package/cpp/MmkvLogger.h: -------------------------------------------------------------------------------- 1 | // 2 | // MmkvLogger.h 3 | // react-native-mmkv 4 | // 5 | // Created by Marc Rousavy on 25.03.24. 6 | // 7 | 8 | #include 9 | 10 | class MmkvLogger { 11 | private: 12 | MmkvLogger() = delete; 13 | 14 | private: 15 | template 16 | static std::string string_format(const std::string& format, Args... args) { 17 | int size_s = std::snprintf(nullptr, 0, format.c_str(), args...) + 1; // Extra space for '\0' 18 | if (size_s <= 0) { 19 | throw std::runtime_error("Failed to format string!"); 20 | } 21 | auto size = static_cast(size_s); 22 | std::unique_ptr buf(new char[size]); 23 | std::snprintf(buf.get(), size, format.c_str(), args...); 24 | return std::string(buf.get(), buf.get() + size - 1); // We don't want the '\0' inside 25 | } 26 | 27 | public: 28 | static void log(const std::string& tag, const std::string& message); 29 | 30 | template 31 | inline static void log(const std::string& tag, const std::string& formatString, Args&&... args) { 32 | std::string formattedString = string_format(formatString, std::forward(args)...); 33 | log(tag, formattedString); 34 | } 35 | }; 36 | -------------------------------------------------------------------------------- /package/cpp/NativeMmkvModule.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // NativeMmkvModule.cpp 3 | // react-native-mmkv 4 | // 5 | // Created by Marc Rousavy on 25.03.2024. 6 | // 7 | 8 | #include "NativeMmkvModule.h" 9 | #include "MMKV.h" 10 | #include "MmkvHostObject.h" 11 | #include "MmkvLogger.h" 12 | 13 | namespace facebook::react { 14 | 15 | NativeMmkvModule::NativeMmkvModule(std::shared_ptr jsInvoker) 16 | : NativeMmkvCxxSpec(jsInvoker) {} 17 | 18 | bool NativeMmkvModule::initialize(jsi::Runtime& runtime, std::string basePath) { 19 | if (basePath.empty()) { 20 | throw jsi::JSError(runtime, "Path cannot be empty!"); 21 | } 22 | 23 | MmkvLogger::log("RNMMKV", "Initializing MMKV at %s...", basePath.c_str()); 24 | 25 | #ifdef DEBUG 26 | MMKVLogLevel logLevel = MMKVLogDebug; 27 | #else 28 | MMKVLogLevel logLevel = MMKVLogWarning; 29 | #endif 30 | 31 | MMKV::initializeMMKV(basePath, logLevel); 32 | 33 | return true; 34 | } 35 | 36 | NativeMmkvModule::~NativeMmkvModule() {} 37 | 38 | jsi::Object NativeMmkvModule::createMMKV(jsi::Runtime& runtime, MMKVConfig config) { 39 | auto instance = std::make_shared(config); 40 | return jsi::Object::createFromHostObject(runtime, instance); 41 | } 42 | 43 | } // namespace facebook::react 44 | -------------------------------------------------------------------------------- /package/cpp/NativeMmkvModule.h: -------------------------------------------------------------------------------- 1 | // 2 | // NativeMmkvModule.h 3 | // react-native-mmkv 4 | // 5 | // Created by Marc Rousavy on 25.03.2024. 6 | // 7 | 8 | #pragma once 9 | 10 | #if __has_include() 11 | // CocoaPods include (iOS) 12 | #include 13 | #elif __has_include() 14 | // CMake include on Android 15 | #include 16 | #else 17 | #error Cannot find react-native-mmkv spec! Try cleaning your cache and re-running CodeGen! 18 | #endif 19 | 20 | namespace facebook::react { 21 | 22 | // The MMKVConfiguration type from JS 23 | using MMKVConfig = 24 | NativeMmkvConfiguration, std::optional, 25 | std::optional, std::optional>; 26 | template <> struct Bridging : NativeMmkvConfigurationBridging {}; 27 | 28 | // The TurboModule itself 29 | class NativeMmkvModule : public NativeMmkvCxxSpec { 30 | public: 31 | NativeMmkvModule(std::shared_ptr jsInvoker); 32 | ~NativeMmkvModule(); 33 | 34 | bool initialize(jsi::Runtime& runtime, std::string basePath); 35 | jsi::Object createMMKV(jsi::Runtime& runtime, MMKVConfig config); 36 | }; 37 | 38 | } // namespace facebook::react 39 | -------------------------------------------------------------------------------- /package/example/.bundle/config: -------------------------------------------------------------------------------- 1 | BUNDLE_PATH: "vendor/bundle" 2 | BUNDLE_FORCE_RUBY_PLATFORM: 1 3 | -------------------------------------------------------------------------------- /package/example/.watchmanconfig: -------------------------------------------------------------------------------- 1 | {} 2 | -------------------------------------------------------------------------------- /package/example/Gemfile: -------------------------------------------------------------------------------- 1 | source 'https://rubygems.org' 2 | 3 | # You may use http://rbenv.org/ or https://rvm.io/ to install and use this version 4 | ruby ">= 2.6.10" 5 | 6 | # Exclude problematic versions of cocoapods and activesupport that causes build failures. 7 | gem 'cocoapods', '>= 1.13', '!= 1.15.0', '!= 1.15.1' 8 | gem 'activesupport', '>= 6.1.7.5', '!= 7.1.0' 9 | gem 'xcodeproj', '< 1.26.0' 10 | gem 'concurrent-ruby', '< 1.3.4' 11 | -------------------------------------------------------------------------------- /package/example/Gemfile.lock: -------------------------------------------------------------------------------- 1 | GEM 2 | remote: https://rubygems.org/ 3 | specs: 4 | CFPropertyList (3.0.7) 5 | base64 6 | nkf 7 | rexml 8 | activesupport (6.1.7.7) 9 | concurrent-ruby (~> 1.0, >= 1.0.2) 10 | i18n (>= 1.6, < 2) 11 | minitest (>= 5.1) 12 | tzinfo (~> 2.0) 13 | zeitwerk (~> 2.3) 14 | addressable (2.8.6) 15 | public_suffix (>= 2.0.2, < 6.0) 16 | algoliasearch (1.27.5) 17 | httpclient (~> 2.8, >= 2.8.3) 18 | json (>= 1.5.1) 19 | atomos (0.1.3) 20 | base64 (0.2.0) 21 | claide (1.1.0) 22 | cocoapods (1.14.3) 23 | addressable (~> 2.8) 24 | claide (>= 1.0.2, < 2.0) 25 | cocoapods-core (= 1.14.3) 26 | cocoapods-deintegrate (>= 1.0.3, < 2.0) 27 | cocoapods-downloader (>= 2.1, < 3.0) 28 | cocoapods-plugins (>= 1.0.0, < 2.0) 29 | cocoapods-search (>= 1.0.0, < 2.0) 30 | cocoapods-trunk (>= 1.6.0, < 2.0) 31 | cocoapods-try (>= 1.1.0, < 2.0) 32 | colored2 (~> 3.1) 33 | escape (~> 0.0.4) 34 | fourflusher (>= 2.3.0, < 3.0) 35 | gh_inspector (~> 1.0) 36 | molinillo (~> 0.8.0) 37 | nap (~> 1.0) 38 | ruby-macho (>= 2.3.0, < 3.0) 39 | xcodeproj (>= 1.23.0, < 2.0) 40 | cocoapods-core (1.14.3) 41 | activesupport (>= 5.0, < 8) 42 | addressable (~> 2.8) 43 | algoliasearch (~> 1.0) 44 | concurrent-ruby (~> 1.1) 45 | fuzzy_match (~> 2.0.4) 46 | nap (~> 1.0) 47 | netrc (~> 0.11) 48 | public_suffix (~> 4.0) 49 | typhoeus (~> 1.0) 50 | cocoapods-deintegrate (1.0.5) 51 | cocoapods-downloader (2.1) 52 | cocoapods-plugins (1.0.0) 53 | nap 54 | cocoapods-search (1.0.1) 55 | cocoapods-trunk (1.6.0) 56 | nap (>= 0.8, < 2.0) 57 | netrc (~> 0.11) 58 | cocoapods-try (1.2.0) 59 | colored2 (3.1.2) 60 | concurrent-ruby (1.2.3) 61 | escape (0.0.4) 62 | ethon (0.16.0) 63 | ffi (>= 1.15.0) 64 | ffi (1.16.3) 65 | fourflusher (2.3.1) 66 | fuzzy_match (2.0.4) 67 | gh_inspector (1.1.3) 68 | httpclient (2.8.3) 69 | i18n (1.14.4) 70 | concurrent-ruby (~> 1.0) 71 | json (2.7.2) 72 | minitest (5.22.3) 73 | molinillo (0.8.0) 74 | nanaimo (0.3.0) 75 | nap (1.1.0) 76 | netrc (0.11.0) 77 | nkf (0.2.0) 78 | public_suffix (4.0.7) 79 | rexml (3.2.6) 80 | ruby-macho (2.5.1) 81 | typhoeus (1.4.1) 82 | ethon (>= 0.9.0) 83 | tzinfo (2.0.6) 84 | concurrent-ruby (~> 1.0) 85 | xcodeproj (1.24.0) 86 | CFPropertyList (>= 2.3.3, < 4.0) 87 | atomos (~> 0.1.3) 88 | claide (>= 1.0.2, < 2.0) 89 | colored2 (~> 3.1) 90 | nanaimo (~> 0.3.0) 91 | rexml (~> 3.2.4) 92 | zeitwerk (2.6.13) 93 | 94 | PLATFORMS 95 | ruby 96 | 97 | DEPENDENCIES 98 | activesupport (>= 6.1.7.5, != 7.1.0) 99 | cocoapods (>= 1.13, != 1.15.1, != 1.15.0) 100 | concurrent-ruby (< 1.3.4) 101 | xcodeproj (< 1.26.0) 102 | 103 | RUBY VERSION 104 | ruby 2.6.10p210 105 | 106 | BUNDLED WITH 107 | 2.3.22 108 | -------------------------------------------------------------------------------- /package/example/README.md: -------------------------------------------------------------------------------- 1 | This is a new [**React Native**](https://reactnative.dev) project, bootstrapped using [`@react-native-community/cli`](https://github.com/react-native-community/cli). 2 | 3 | # Getting Started 4 | 5 | >**Note**: Make sure you have completed the [React Native - Environment Setup](https://reactnative.dev/docs/environment-setup) instructions till "Creating a new application" step, before proceeding. 6 | 7 | ## Step 1: Start the Metro Server 8 | 9 | First, you will need to start **Metro**, the JavaScript _bundler_ that ships _with_ React Native. 10 | 11 | To start Metro, run the following command from the _root_ of your React Native project: 12 | 13 | ```bash 14 | # using npm 15 | npm start 16 | 17 | # OR using Yarn 18 | yarn start 19 | ``` 20 | 21 | ## Step 2: Start your Application 22 | 23 | Let Metro Bundler run in its _own_ terminal. Open a _new_ terminal from the _root_ of your React Native project. Run the following command to start your _Android_ or _iOS_ app: 24 | 25 | ### For Android 26 | 27 | ```bash 28 | # using npm 29 | npm run android 30 | 31 | # OR using Yarn 32 | yarn android 33 | ``` 34 | 35 | ### For iOS 36 | 37 | ```bash 38 | # using npm 39 | npm run ios 40 | 41 | # OR using Yarn 42 | yarn ios 43 | ``` 44 | 45 | If everything is set up _correctly_, you should see your new app running in your _Android Emulator_ or _iOS Simulator_ shortly provided you have set up your emulator/simulator correctly. 46 | 47 | This is one way to run your app — you can also run it directly from within Android Studio and Xcode respectively. 48 | 49 | ## Step 3: Modifying your App 50 | 51 | Now that you have successfully run the app, let's modify it. 52 | 53 | 1. Open `App.tsx` in your text editor of choice and edit some lines. 54 | 2. For **Android**: Press the R key twice or select **"Reload"** from the **Developer Menu** (Ctrl + M (on Window and Linux) or Cmd ⌘ + M (on macOS)) to see your changes! 55 | 56 | For **iOS**: Hit Cmd ⌘ + R in your iOS Simulator to reload the app and see your changes! 57 | 58 | ## Congratulations! :tada: 59 | 60 | You've successfully run and modified your React Native App. :partying_face: 61 | 62 | ### Now what? 63 | 64 | - 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). 65 | - If you're curious to learn more about React Native, check out the [Introduction to React Native](https://reactnative.dev/docs/getting-started). 66 | 67 | # Troubleshooting 68 | 69 | If you can't get this to work, see the [Troubleshooting](https://reactnative.dev/docs/troubleshooting) page. 70 | 71 | # Learn More 72 | 73 | To learn more about React Native, take a look at the following resources: 74 | 75 | - [React Native Website](https://reactnative.dev) - learn more about React Native. 76 | - [Getting Started](https://reactnative.dev/docs/environment-setup) - an **overview** of React Native and how setup your environment. 77 | - [Learn the Basics](https://reactnative.dev/docs/getting-started) - a **guided tour** of the React Native **basics**. 78 | - [Blog](https://reactnative.dev/blog) - read the latest official React Native **Blog** posts. 79 | - [`@facebook/react-native`](https://github.com/facebook/react-native) - the Open Source; GitHub **repository** for React Native. 80 | -------------------------------------------------------------------------------- /package/example/android/app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: "com.android.application" 2 | apply plugin: "org.jetbrains.kotlin.android" 3 | apply plugin: "com.facebook.react" 4 | 5 | /** 6 | * This is the configuration block to customize your React Native Android app. 7 | * By default you don't need to apply any configuration, just uncomment the lines you need. 8 | */ 9 | react { 10 | /* Folders */ 11 | // The root of your project, i.e. where "package.json" lives. Default is '..' 12 | // root = file("../") 13 | // The folder where the react-native NPM package is. Default is ../node_modules/react-native 14 | // reactNativeDir = file("../node_modules/react-native") 15 | // The folder where the react-native Codegen package is. Default is ../node_modules/@react-native/codegen 16 | // codegenDir = file("../node_modules/@react-native/codegen") 17 | // The cli.js file which is the React Native CLI entrypoint. Default is ../node_modules/react-native/cli.js 18 | // cliFile = file("../node_modules/react-native/cli.js") 19 | 20 | /* Variants */ 21 | // The list of variants to that are debuggable. For those we're going to 22 | // skip the bundling of the JS bundle and the assets. By default is just 'debug'. 23 | // If you add flavors like lite, prod, etc. you'll have to list your debuggableVariants. 24 | // debuggableVariants = ["liteDebug", "prodDebug"] 25 | 26 | /* Bundling */ 27 | // A list containing the node command and its flags. Default is just 'node'. 28 | // nodeExecutableAndArgs = ["node"] 29 | // 30 | // The command to run when bundling. By default is 'bundle' 31 | // bundleCommand = "ram-bundle" 32 | // 33 | // The path to the CLI configuration file. Default is empty. 34 | // bundleConfig = file(../rn-cli.config.js) 35 | // 36 | // The name of the generated asset file containing your JS bundle 37 | // bundleAssetName = "MyApplication.android.bundle" 38 | // 39 | // The entry file for bundle generation. Default is 'index.android.js' or 'index.js' 40 | // entryFile = file("../js/MyApplication.android.js") 41 | // 42 | // A list of extra flags to pass to the 'bundle' commands. 43 | // See https://github.com/react-native-community/cli/blob/main/docs/commands.md#bundle 44 | // extraPackagerArgs = [] 45 | 46 | /* Hermes Commands */ 47 | // The hermes compiler command to run. By default it is 'hermesc' 48 | // hermesCommand = "$rootDir/my-custom-hermesc/bin/hermesc" 49 | // 50 | // The list of flags to pass to the Hermes compiler. By default is "-O", "-output-source-map" 51 | // hermesFlags = ["-O", "-output-source-map"] 52 | 53 | /* Autolinking */ 54 | autolinkLibrariesWithApp() 55 | } 56 | 57 | /** 58 | * Set this to true to Run Proguard on Release builds to minify the Java bytecode. 59 | */ 60 | def enableProguardInReleaseBuilds = false 61 | 62 | /** 63 | * The preferred build flavor of JavaScriptCore (JSC) 64 | * 65 | * For example, to use the international variant, you can use: 66 | * `def jscFlavor = 'org.webkit:android-jsc-intl:+'` 67 | * 68 | * The international variant includes ICU i18n library and necessary data 69 | * allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that 70 | * give correct results when using with locales other than en-US. Note that 71 | * this variant is about 6MiB larger per architecture than default. 72 | */ 73 | def jscFlavor = 'org.webkit:android-jsc:+' 74 | 75 | android { 76 | ndkVersion rootProject.ext.ndkVersion 77 | buildToolsVersion rootProject.ext.buildToolsVersion 78 | compileSdk rootProject.ext.compileSdkVersion 79 | 80 | namespace "com.mrousavy.mmkvexample" 81 | defaultConfig { 82 | applicationId "com.mrousavy.mmkvexample" 83 | minSdkVersion rootProject.ext.minSdkVersion 84 | targetSdkVersion rootProject.ext.targetSdkVersion 85 | versionCode 1 86 | versionName "1.0" 87 | } 88 | signingConfigs { 89 | debug { 90 | storeFile file('debug.keystore') 91 | storePassword 'android' 92 | keyAlias 'androiddebugkey' 93 | keyPassword 'android' 94 | } 95 | } 96 | buildTypes { 97 | debug { 98 | signingConfig signingConfigs.debug 99 | } 100 | release { 101 | // Caution! In production, you need to generate your own keystore file. 102 | // see https://reactnative.dev/docs/signed-apk-android. 103 | signingConfig signingConfigs.debug 104 | minifyEnabled enableProguardInReleaseBuilds 105 | proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro" 106 | } 107 | } 108 | } 109 | 110 | dependencies { 111 | // The version of react-native is set by the React Native Gradle Plugin 112 | implementation("com.facebook.react:react-android") 113 | 114 | if (hermesEnabled.toBoolean()) { 115 | implementation("com.facebook.react:hermes-android") 116 | } else { 117 | implementation jscFlavor 118 | } 119 | } 120 | -------------------------------------------------------------------------------- /package/example/android/app/debug.keystore: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mrousavy/react-native-mmkv/fefb2db7e8bd281998a38cb0a65704455c443446/package/example/android/app/debug.keystore -------------------------------------------------------------------------------- /package/example/android/app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in /usr/local/Cellar/android-sdk/24.3.3/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | -------------------------------------------------------------------------------- /package/example/android/app/src/debug/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 9 | 10 | -------------------------------------------------------------------------------- /package/example/android/app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 12 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /package/example/android/app/src/main/java/com/mrousavy/mmkvexample/MainActivity.kt: -------------------------------------------------------------------------------- 1 | package com.mrousavy.mmkvexample 2 | 3 | import com.facebook.react.ReactActivity 4 | import com.facebook.react.ReactActivityDelegate 5 | import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.fabricEnabled 6 | import com.facebook.react.defaults.DefaultReactActivityDelegate 7 | 8 | class MainActivity : ReactActivity() { 9 | 10 | /** 11 | * Returns the name of the main component registered from JavaScript. This is used to schedule 12 | * rendering of the component. 13 | */ 14 | override fun getMainComponentName(): String = "MmkvExample" 15 | 16 | /** 17 | * Returns the instance of the [ReactActivityDelegate]. We use [DefaultReactActivityDelegate] 18 | * which allows you to enable New Architecture with a single boolean flags [fabricEnabled] 19 | */ 20 | override fun createReactActivityDelegate(): ReactActivityDelegate = 21 | DefaultReactActivityDelegate(this, mainComponentName, fabricEnabled) 22 | } 23 | -------------------------------------------------------------------------------- /package/example/android/app/src/main/java/com/mrousavy/mmkvexample/MainApplication.kt: -------------------------------------------------------------------------------- 1 | package com.mrousavy.mmkvexample 2 | 3 | import android.app.Application 4 | import com.facebook.react.PackageList 5 | import com.facebook.react.ReactApplication 6 | import com.facebook.react.ReactHost 7 | import com.facebook.react.ReactNativeHost 8 | import com.facebook.react.ReactPackage 9 | import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.load 10 | import com.facebook.react.defaults.DefaultReactHost.getDefaultReactHost 11 | import com.facebook.react.defaults.DefaultReactNativeHost 12 | import com.facebook.react.soloader.OpenSourceMergedSoMapping 13 | import com.facebook.soloader.SoLoader 14 | 15 | class MainApplication : Application(), ReactApplication { 16 | 17 | override val reactNativeHost: ReactNativeHost = 18 | object : DefaultReactNativeHost(this) { 19 | override fun getPackages(): List = 20 | PackageList(this).packages.apply { 21 | // Packages that cannot be autolinked yet can be added manually here, for example: 22 | // add(MyReactNativePackage()) 23 | } 24 | 25 | override fun getJSMainModuleName(): String = "index" 26 | 27 | override fun getUseDeveloperSupport(): Boolean = BuildConfig.DEBUG 28 | 29 | override val isNewArchEnabled: Boolean = BuildConfig.IS_NEW_ARCHITECTURE_ENABLED 30 | override val isHermesEnabled: Boolean = BuildConfig.IS_HERMES_ENABLED 31 | } 32 | 33 | override val reactHost: ReactHost 34 | get() = getDefaultReactHost(this.applicationContext, reactNativeHost) 35 | 36 | override fun onCreate() { 37 | super.onCreate() 38 | SoLoader.init(this, OpenSourceMergedSoMapping) 39 | if (BuildConfig.IS_NEW_ARCHITECTURE_ENABLED) { 40 | // If you opted-in for the New Architecture, we load the native entry point for this app. 41 | load() 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /package/example/android/app/src/main/res/drawable/rn_edit_text_material.xml: -------------------------------------------------------------------------------- 1 | 2 | 16 | 21 | 22 | 23 | 32 | 33 | 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /package/example/android/app/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mrousavy/react-native-mmkv/fefb2db7e8bd281998a38cb0a65704455c443446/package/example/android/app/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /package/example/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mrousavy/react-native-mmkv/fefb2db7e8bd281998a38cb0a65704455c443446/package/example/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /package/example/android/app/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mrousavy/react-native-mmkv/fefb2db7e8bd281998a38cb0a65704455c443446/package/example/android/app/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /package/example/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mrousavy/react-native-mmkv/fefb2db7e8bd281998a38cb0a65704455c443446/package/example/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /package/example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mrousavy/react-native-mmkv/fefb2db7e8bd281998a38cb0a65704455c443446/package/example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /package/example/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mrousavy/react-native-mmkv/fefb2db7e8bd281998a38cb0a65704455c443446/package/example/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /package/example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mrousavy/react-native-mmkv/fefb2db7e8bd281998a38cb0a65704455c443446/package/example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /package/example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mrousavy/react-native-mmkv/fefb2db7e8bd281998a38cb0a65704455c443446/package/example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /package/example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mrousavy/react-native-mmkv/fefb2db7e8bd281998a38cb0a65704455c443446/package/example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /package/example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mrousavy/react-native-mmkv/fefb2db7e8bd281998a38cb0a65704455c443446/package/example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /package/example/android/app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | MmkvExample 3 | 4 | -------------------------------------------------------------------------------- /package/example/android/app/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /package/example/android/build.gradle: -------------------------------------------------------------------------------- 1 | buildscript { 2 | ext { 3 | buildToolsVersion = "35.0.0" 4 | minSdkVersion = 24 5 | compileSdkVersion = 35 6 | targetSdkVersion = 34 7 | ndkVersion = "27.1.12297006" 8 | kotlinVersion = "2.0.21" 9 | } 10 | repositories { 11 | google() 12 | mavenCentral() 13 | } 14 | dependencies { 15 | classpath("com.android.tools.build:gradle") 16 | classpath("com.facebook.react:react-native-gradle-plugin") 17 | classpath("org.jetbrains.kotlin:kotlin-gradle-plugin") 18 | } 19 | } 20 | 21 | apply plugin: "com.facebook.react.rootproject" 22 | -------------------------------------------------------------------------------- /package/example/android/gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | 3 | # IDE (e.g. Android Studio) users: 4 | # Gradle settings configured through the IDE *will override* 5 | # any settings specified in this file. 6 | 7 | # For more details on how to configure your build environment visit 8 | # http://www.gradle.org/docs/current/userguide/build_environment.html 9 | 10 | # Specifies the JVM arguments used for the daemon process. 11 | # The setting is particularly useful for tweaking memory settings. 12 | # Default value: -Xmx512m -XX:MaxMetaspaceSize=256m 13 | org.gradle.jvmargs=-Xmx4096m -Xms512M -XX:MaxMetaspaceSize=1g 14 | 15 | # When configured, Gradle will run in incubating parallel mode. 16 | # This option should only be used with decoupled projects. More details, visit 17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 18 | # org.gradle.parallel=true 19 | 20 | # AndroidX package structure to make it clearer which packages are bundled with the 21 | # Android operating system, and which are packaged with your app's APK 22 | # https://developer.android.com/topic/libraries/support-library/androidx-rn 23 | android.useAndroidX=true 24 | 25 | # Use this property to specify which architecture you want to build. 26 | # You can also override it from the CLI using 27 | # ./gradlew -PreactNativeArchitectures=x86_64 28 | reactNativeArchitectures=armeabi-v7a,arm64-v8a,x86,x86_64 29 | 30 | # Use this property to enable support to the new architecture. 31 | # This will allow you to use TurboModules and the Fabric render in 32 | # your application. You should enable this flag either if you want 33 | # to write custom TurboModules/Fabric components OR use libraries that 34 | # are providing them. 35 | newArchEnabled=true 36 | 37 | # Use this property to enable or disable the Hermes JS engine. 38 | # If set to false, you will be using JSC instead. 39 | hermesEnabled=true 40 | -------------------------------------------------------------------------------- /package/example/android/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mrousavy/react-native-mmkv/fefb2db7e8bd281998a38cb0a65704455c443446/package/example/android/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /package/example/android/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.10.2-all.zip 4 | networkTimeout=10000 5 | validateDistributionUrl=true 6 | zipStoreBase=GRADLE_USER_HOME 7 | zipStorePath=wrapper/dists 8 | -------------------------------------------------------------------------------- /package/example/android/gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | # SPDX-License-Identifier: Apache-2.0 19 | # 20 | 21 | ############################################################################## 22 | # 23 | # Gradle start up script for POSIX generated by Gradle. 24 | # 25 | # Important for running: 26 | # 27 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 28 | # noncompliant, but you have some other compliant shell such as ksh or 29 | # bash, then to run this script, type that shell name before the whole 30 | # command line, like: 31 | # 32 | # ksh Gradle 33 | # 34 | # Busybox and similar reduced shells will NOT work, because this script 35 | # requires all of these POSIX shell features: 36 | # * functions; 37 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 38 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 39 | # * compound commands having a testable exit status, especially «case»; 40 | # * various built-in commands including «command», «set», and «ulimit». 41 | # 42 | # Important for patching: 43 | # 44 | # (2) This script targets any POSIX shell, so it avoids extensions provided 45 | # by Bash, Ksh, etc; in particular arrays are avoided. 46 | # 47 | # The "traditional" practice of packing multiple parameters into a 48 | # space-separated string is a well documented source of bugs and security 49 | # problems, so this is (mostly) avoided, by progressively accumulating 50 | # options in "$@", and eventually passing that to Java. 51 | # 52 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 53 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 54 | # see the in-line comments for details. 55 | # 56 | # There are tweaks for specific operating systems such as AIX, CygWin, 57 | # Darwin, MinGW, and NonStop. 58 | # 59 | # (3) This script is generated from the Groovy template 60 | # https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 61 | # within the Gradle project. 62 | # 63 | # You can find Gradle at https://github.com/gradle/gradle/. 64 | # 65 | ############################################################################## 66 | 67 | # Attempt to set APP_HOME 68 | 69 | # Resolve links: $0 may be a link 70 | app_path=$0 71 | 72 | # Need this for daisy-chained symlinks. 73 | while 74 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 75 | [ -h "$app_path" ] 76 | do 77 | ls=$( ls -ld "$app_path" ) 78 | link=${ls#*' -> '} 79 | case $link in #( 80 | /*) app_path=$link ;; #( 81 | *) app_path=$APP_HOME$link ;; 82 | esac 83 | done 84 | 85 | # This is normally unused 86 | # shellcheck disable=SC2034 87 | APP_BASE_NAME=${0##*/} 88 | # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) 89 | APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s 90 | ' "$PWD" ) || exit 91 | 92 | # Use the maximum available, or set MAX_FD != -1 to use that value. 93 | MAX_FD=maximum 94 | 95 | warn () { 96 | echo "$*" 97 | } >&2 98 | 99 | die () { 100 | echo 101 | echo "$*" 102 | echo 103 | exit 1 104 | } >&2 105 | 106 | # OS specific support (must be 'true' or 'false'). 107 | cygwin=false 108 | msys=false 109 | darwin=false 110 | nonstop=false 111 | case "$( uname )" in #( 112 | CYGWIN* ) cygwin=true ;; #( 113 | Darwin* ) darwin=true ;; #( 114 | MSYS* | MINGW* ) msys=true ;; #( 115 | NONSTOP* ) nonstop=true ;; 116 | esac 117 | 118 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 119 | 120 | 121 | # Determine the Java command to use to start the JVM. 122 | if [ -n "$JAVA_HOME" ] ; then 123 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 124 | # IBM's JDK on AIX uses strange locations for the executables 125 | JAVACMD=$JAVA_HOME/jre/sh/java 126 | else 127 | JAVACMD=$JAVA_HOME/bin/java 128 | fi 129 | if [ ! -x "$JAVACMD" ] ; then 130 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 131 | 132 | Please set the JAVA_HOME variable in your environment to match the 133 | location of your Java installation." 134 | fi 135 | else 136 | JAVACMD=java 137 | if ! command -v java >/dev/null 2>&1 138 | then 139 | die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 140 | 141 | Please set the JAVA_HOME variable in your environment to match the 142 | location of your Java installation." 143 | fi 144 | fi 145 | 146 | # Increase the maximum file descriptors if we can. 147 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 148 | case $MAX_FD in #( 149 | max*) 150 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. 151 | # shellcheck disable=SC2039,SC3045 152 | MAX_FD=$( ulimit -H -n ) || 153 | warn "Could not query maximum file descriptor limit" 154 | esac 155 | case $MAX_FD in #( 156 | '' | soft) :;; #( 157 | *) 158 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. 159 | # shellcheck disable=SC2039,SC3045 160 | ulimit -n "$MAX_FD" || 161 | warn "Could not set maximum file descriptor limit to $MAX_FD" 162 | esac 163 | fi 164 | 165 | # Collect all arguments for the java command, stacking in reverse order: 166 | # * args from the command line 167 | # * the main class name 168 | # * -classpath 169 | # * -D...appname settings 170 | # * --module-path (only if needed) 171 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 172 | 173 | # For Cygwin or MSYS, switch paths to Windows format before running java 174 | if "$cygwin" || "$msys" ; then 175 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 176 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 177 | 178 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 179 | 180 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 181 | for arg do 182 | if 183 | case $arg in #( 184 | -*) false ;; # don't mess with options #( 185 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 186 | [ -e "$t" ] ;; #( 187 | *) false ;; 188 | esac 189 | then 190 | arg=$( cygpath --path --ignore --mixed "$arg" ) 191 | fi 192 | # Roll the args list around exactly as many times as the number of 193 | # args, so each arg winds up back in the position where it started, but 194 | # possibly modified. 195 | # 196 | # NB: a `for` loop captures its iteration list before it begins, so 197 | # changing the positional parameters here affects neither the number of 198 | # iterations, nor the values presented in `arg`. 199 | shift # remove old arg 200 | set -- "$@" "$arg" # push replacement arg 201 | done 202 | fi 203 | 204 | 205 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 206 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 207 | 208 | # Collect all arguments for the java command: 209 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, 210 | # and any embedded shellness will be escaped. 211 | # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be 212 | # treated as '${Hostname}' itself on the command line. 213 | 214 | set -- \ 215 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 216 | -classpath "$CLASSPATH" \ 217 | org.gradle.wrapper.GradleWrapperMain \ 218 | "$@" 219 | 220 | # Stop when "xargs" is not available. 221 | if ! command -v xargs >/dev/null 2>&1 222 | then 223 | die "xargs is not available" 224 | fi 225 | 226 | # Use "xargs" to parse quoted args. 227 | # 228 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 229 | # 230 | # In Bash we could simply go: 231 | # 232 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 233 | # set -- "${ARGS[@]}" "$@" 234 | # 235 | # but POSIX shell has neither arrays nor command substitution, so instead we 236 | # post-process each arg (as a line of input to sed) to backslash-escape any 237 | # character that might be a shell metacharacter, then use eval to reverse 238 | # that process (while maintaining the separation between arguments), and wrap 239 | # the whole thing up as a single "set" statement. 240 | # 241 | # This will of course break if any of these variables contains a newline or 242 | # an unmatched quote. 243 | # 244 | 245 | eval "set -- $( 246 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 247 | xargs -n1 | 248 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 249 | tr '\n' ' ' 250 | )" '"$@"' 251 | 252 | exec "$JAVACMD" "$@" 253 | -------------------------------------------------------------------------------- /package/example/android/gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | @rem SPDX-License-Identifier: Apache-2.0 17 | @rem 18 | 19 | @if "%DEBUG%"=="" @echo off 20 | @rem ########################################################################## 21 | @rem 22 | @rem Gradle startup script for Windows 23 | @rem 24 | @rem ########################################################################## 25 | 26 | @rem Set local scope for the variables with windows NT shell 27 | if "%OS%"=="Windows_NT" setlocal 28 | 29 | set DIRNAME=%~dp0 30 | if "%DIRNAME%"=="" set DIRNAME=. 31 | @rem This is normally unused 32 | set APP_BASE_NAME=%~n0 33 | set APP_HOME=%DIRNAME% 34 | 35 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 36 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 37 | 38 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 39 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 40 | 41 | @rem Find java.exe 42 | if defined JAVA_HOME goto findJavaFromJavaHome 43 | 44 | set JAVA_EXE=java.exe 45 | %JAVA_EXE% -version >NUL 2>&1 46 | if %ERRORLEVEL% equ 0 goto execute 47 | 48 | echo. 1>&2 49 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 50 | echo. 1>&2 51 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 52 | echo location of your Java installation. 1>&2 53 | 54 | goto fail 55 | 56 | :findJavaFromJavaHome 57 | set JAVA_HOME=%JAVA_HOME:"=% 58 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 59 | 60 | if exist "%JAVA_EXE%" goto execute 61 | 62 | echo. 1>&2 63 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 64 | echo. 1>&2 65 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 66 | echo location of your Java installation. 1>&2 67 | 68 | goto fail 69 | 70 | :execute 71 | @rem Setup the command line 72 | 73 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 74 | 75 | 76 | @rem Execute Gradle 77 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 78 | 79 | :end 80 | @rem End local scope for the variables with windows NT shell 81 | if %ERRORLEVEL% equ 0 goto mainEnd 82 | 83 | :fail 84 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 85 | rem the _cmd.exe /c_ return code! 86 | set EXIT_CODE=%ERRORLEVEL% 87 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 88 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 89 | exit /b %EXIT_CODE% 90 | 91 | :mainEnd 92 | if "%OS%"=="Windows_NT" endlocal 93 | 94 | :omega 95 | -------------------------------------------------------------------------------- /package/example/android/settings.gradle: -------------------------------------------------------------------------------- 1 | pluginManagement { includeBuild("../node_modules/@react-native/gradle-plugin") } 2 | plugins { id("com.facebook.react.settings") } 3 | extensions.configure(com.facebook.react.ReactSettingsExtension){ ex -> ex.autolinkLibrariesFromCommand() } 4 | 5 | rootProject.name = 'MmkvExample' 6 | 7 | include ':app' 8 | includeBuild('../node_modules/@react-native/gradle-plugin') 9 | -------------------------------------------------------------------------------- /package/example/app.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "MmkvExample", 3 | "displayName": "MmkvExample" 4 | } 5 | -------------------------------------------------------------------------------- /package/example/babel.config.js: -------------------------------------------------------------------------------- 1 | const path = require('path'); 2 | const pak = require('../package.json'); 3 | 4 | module.exports = { 5 | presets: ['module:@react-native/babel-preset'], 6 | plugins: [ 7 | [ 8 | 'module-resolver', 9 | { 10 | extensions: ['.tsx', '.ts', '.js', '.json'], 11 | alias: { 12 | [pak.name]: path.join(__dirname, '..', pak.source), 13 | }, 14 | }, 15 | ], 16 | ], 17 | }; 18 | -------------------------------------------------------------------------------- /package/example/index.js: -------------------------------------------------------------------------------- 1 | import { AppRegistry } from 'react-native'; 2 | import App from './src/App'; 3 | import { name as appName } from './app.json'; 4 | 5 | AppRegistry.registerComponent(appName, () => App); 6 | -------------------------------------------------------------------------------- /package/example/ios/.xcode.env: -------------------------------------------------------------------------------- 1 | # This `.xcode.env` file is versioned and is used to source the environment 2 | # used when running script phases inside Xcode. 3 | # To customize your local environment, you can create an `.xcode.env.local` 4 | # file that is not versioned. 5 | 6 | # NODE_BINARY variable contains the PATH to the node executable. 7 | # 8 | # Customize the NODE_BINARY variable here. 9 | # For example, to use nvm with brew, add the following line 10 | # . "$(brew --prefix nvm)/nvm.sh" --no-use 11 | export NODE_BINARY=$(command -v node) 12 | -------------------------------------------------------------------------------- /package/example/ios/.xcode.env.local: -------------------------------------------------------------------------------- 1 | export NODE_BINARY=/Users/mrousavy/.nvm/versions/node/v20.10.0/bin/node 2 | -------------------------------------------------------------------------------- /package/example/ios/AppDelegate.swift: -------------------------------------------------------------------------------- 1 | // 2 | // AppDelegate.swift 3 | // MmkvExample 4 | // 5 | // Created by Marc Rousavy on 16.02.25. 6 | // 7 | 8 | import UIKit 9 | import React 10 | import React_RCTAppDelegate 11 | import ReactAppDependencyProvider 12 | 13 | @main 14 | class AppDelegate: RCTAppDelegate { 15 | override func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool { 16 | self.moduleName = "MmkvExample" 17 | self.dependencyProvider = RCTAppDependencyProvider() 18 | 19 | // You can add your custom initial props in the dictionary below. 20 | // They will be passed down to the ViewController used by React Native. 21 | self.initialProps = [:] 22 | 23 | return super.application(application, didFinishLaunchingWithOptions: launchOptions) 24 | } 25 | 26 | override func sourceURL(for bridge: RCTBridge) -> URL? { 27 | self.bundleURL() 28 | } 29 | 30 | override func bundleURL() -> URL? { 31 | #if DEBUG 32 | RCTBundleURLProvider.sharedSettings().jsBundleURL(forBundleRoot: "index") 33 | #else 34 | Bundle.main.url(forResource: "main", withExtension: "jsbundle") 35 | #endif 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /package/example/ios/File.swift: -------------------------------------------------------------------------------- 1 | // 2 | // File.swift 3 | // MmkvExample 4 | // 5 | 6 | import Foundation 7 | -------------------------------------------------------------------------------- /package/example/ios/MmkvExample-Bridging-Header.h: -------------------------------------------------------------------------------- 1 | // 2 | // Use this file to import your target's public headers that you would like to expose to Swift. 3 | // 4 | -------------------------------------------------------------------------------- /package/example/ios/MmkvExample.xcodeproj/xcshareddata/xcschemes/MmkvExample.xcscheme: -------------------------------------------------------------------------------- 1 | 2 | 5 | 8 | 9 | 15 | 21 | 22 | 23 | 24 | 25 | 30 | 31 | 33 | 39 | 40 | 41 | 42 | 43 | 53 | 55 | 61 | 62 | 63 | 64 | 70 | 72 | 78 | 79 | 80 | 81 | 83 | 84 | 87 | 88 | 89 | -------------------------------------------------------------------------------- /package/example/ios/MmkvExample.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /package/example/ios/MmkvExample.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | IDEDidComputeMac32BitWarning 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /package/example/ios/MmkvExample/Images.xcassets/AppIcon.appiconset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "idiom" : "iphone", 5 | "scale" : "2x", 6 | "size" : "20x20" 7 | }, 8 | { 9 | "idiom" : "iphone", 10 | "scale" : "3x", 11 | "size" : "20x20" 12 | }, 13 | { 14 | "idiom" : "iphone", 15 | "scale" : "2x", 16 | "size" : "29x29" 17 | }, 18 | { 19 | "idiom" : "iphone", 20 | "scale" : "3x", 21 | "size" : "29x29" 22 | }, 23 | { 24 | "idiom" : "iphone", 25 | "scale" : "2x", 26 | "size" : "40x40" 27 | }, 28 | { 29 | "idiom" : "iphone", 30 | "scale" : "3x", 31 | "size" : "40x40" 32 | }, 33 | { 34 | "idiom" : "iphone", 35 | "scale" : "2x", 36 | "size" : "60x60" 37 | }, 38 | { 39 | "idiom" : "iphone", 40 | "scale" : "3x", 41 | "size" : "60x60" 42 | }, 43 | { 44 | "idiom" : "ios-marketing", 45 | "scale" : "1x", 46 | "size" : "1024x1024" 47 | } 48 | ], 49 | "info" : { 50 | "author" : "xcode", 51 | "version" : 1 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /package/example/ios/MmkvExample/Images.xcassets/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "info" : { 3 | "version" : 1, 4 | "author" : "xcode" 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /package/example/ios/MmkvExample/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleDisplayName 8 | MmkvExample 9 | CFBundleExecutable 10 | $(EXECUTABLE_NAME) 11 | CFBundleIdentifier 12 | $(PRODUCT_BUNDLE_IDENTIFIER) 13 | CFBundleInfoDictionaryVersion 14 | 6.0 15 | CFBundleName 16 | $(PRODUCT_NAME) 17 | CFBundlePackageType 18 | APPL 19 | CFBundleShortVersionString 20 | $(MARKETING_VERSION) 21 | CFBundleSignature 22 | ???? 23 | CFBundleVersion 24 | $(CURRENT_PROJECT_VERSION) 25 | LSRequiresIPhoneOS 26 | 27 | NSAppTransportSecurity 28 | 29 | NSAllowsArbitraryLoads 30 | 31 | NSAllowsLocalNetworking 32 | 33 | 34 | NSLocationWhenInUseUsageDescription 35 | 36 | UILaunchStoryboardName 37 | LaunchScreen 38 | UIRequiredDeviceCapabilities 39 | 40 | arm64 41 | 42 | UISupportedInterfaceOrientations 43 | 44 | UIInterfaceOrientationPortrait 45 | UIInterfaceOrientationLandscapeLeft 46 | UIInterfaceOrientationLandscapeRight 47 | 48 | UIViewControllerBasedStatusBarAppearance 49 | 50 | 51 | 52 | -------------------------------------------------------------------------------- /package/example/ios/MmkvExample/LaunchScreen.storyboard: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 24 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /package/example/ios/Podfile: -------------------------------------------------------------------------------- 1 | ENV['RCT_NEW_ARCH_ENABLED'] = '1' 2 | 3 | # Resolve react_native_pods.rb with node to allow for hoisting 4 | require Pod::Executable.execute_command('node', ['-p', 5 | 'require.resolve( 6 | "react-native/scripts/react_native_pods.rb", 7 | {paths: [process.argv[1]]}, 8 | )', __dir__]).strip 9 | 10 | platform :ios, min_ios_version_supported 11 | prepare_react_native_project! 12 | 13 | linkage = ENV['USE_FRAMEWORKS'] 14 | if linkage != nil 15 | Pod::UI.puts "Configuring Pod with #{linkage}ally linked Frameworks".green 16 | use_frameworks! :linkage => linkage.to_sym 17 | end 18 | 19 | target 'MmkvExample' do 20 | config = use_native_modules! 21 | 22 | use_react_native!( 23 | :path => config[:reactNativePath], 24 | # An absolute path to your application root. 25 | :app_path => "#{Pod::Config.instance.installation_root}/.." 26 | ) 27 | 28 | post_install do |installer| 29 | # https://github.com/facebook/react-native/blob/main/packages/react-native/scripts/react_native_pods.rb#L197-L202 30 | react_native_post_install( 31 | installer, 32 | config[:reactNativePath], 33 | :mac_catalyst_enabled => false, 34 | # :ccache_enabled => true 35 | ) 36 | end 37 | end 38 | -------------------------------------------------------------------------------- /package/example/ios/PrivacyInfo.xcprivacy: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | NSPrivacyAccessedAPITypes 6 | 7 | 8 | NSPrivacyAccessedAPIType 9 | NSPrivacyAccessedAPICategoryFileTimestamp 10 | NSPrivacyAccessedAPITypeReasons 11 | 12 | C617.1 13 | 14 | 15 | 16 | NSPrivacyAccessedAPIType 17 | NSPrivacyAccessedAPICategoryUserDefaults 18 | NSPrivacyAccessedAPITypeReasons 19 | 20 | CA92.1 21 | 22 | 23 | 24 | NSPrivacyAccessedAPIType 25 | NSPrivacyAccessedAPICategorySystemBootTime 26 | NSPrivacyAccessedAPITypeReasons 27 | 28 | 35F9.1 29 | 30 | 31 | 32 | NSPrivacyCollectedDataTypes 33 | 34 | NSPrivacyTracking 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /package/example/jest.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | preset: 'react-native', 3 | }; 4 | -------------------------------------------------------------------------------- /package/example/metro.config.js: -------------------------------------------------------------------------------- 1 | const { getDefaultConfig, mergeConfig } = require('@react-native/metro-config'); 2 | const path = require('path'); 3 | const escape = require('escape-string-regexp'); 4 | const exclusionList = require('metro-config/src/defaults/exclusionList'); 5 | const pak = require('../package.json'); 6 | 7 | const root = path.resolve(__dirname, '..'); 8 | const modules = Object.keys({ ...pak.peerDependencies }); 9 | 10 | /** 11 | * Metro configuration 12 | * https://reactnative.dev/docs/metro 13 | * 14 | * @type {import('metro-config').MetroConfig} 15 | */ 16 | const config = { 17 | watchFolders: [root], 18 | 19 | // We need to make sure that only one version is loaded for peerDependencies 20 | // So we block them at the root, and alias them to the versions in example's node_modules 21 | resolver: { 22 | blacklistRE: exclusionList( 23 | modules.map( 24 | (m) => 25 | new RegExp(`^${escape(path.join(root, 'node_modules', m))}\\/.*$`) 26 | ) 27 | ), 28 | 29 | extraNodeModules: modules.reduce((acc, name) => { 30 | acc[name] = path.join(__dirname, 'node_modules', name); 31 | return acc; 32 | }, {}), 33 | }, 34 | 35 | transformer: { 36 | getTransformOptions: async () => ({ 37 | transform: { 38 | experimentalImportSupport: false, 39 | inlineRequires: true, 40 | }, 41 | }), 42 | }, 43 | }; 44 | 45 | module.exports = mergeConfig(getDefaultConfig(__dirname), config); 46 | -------------------------------------------------------------------------------- /package/example/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "react-native-mmkv-example", 3 | "version": "0.0.1", 4 | "private": true, 5 | "scripts": { 6 | "android": "react-native run-android", 7 | "ios": "react-native run-ios", 8 | "pods": "cd ios && bundle install && RCT_NEW_ARCH_ENABLED=1 bundle exec pod install", 9 | "start": "react-native start", 10 | "build:android": "cd android && ./gradlew assembleDebug --no-daemon --console=plain -PreactNativeArchitectures=arm64-v8a", 11 | "build:ios": "cd ios && xcodebuild -workspace MmkvExample.xcworkspace -scheme MmkvExample -configuration Debug -sdk iphonesimulator CC=clang CPLUSPLUS=clang++ LD=clang LDPLUSPLUS=clang++ GCC_OPTIMIZATION_LEVEL=0 GCC_PRECOMPILE_PREFIX_HEADER=YES ASSETCATALOG_COMPILER_OPTIMIZATION=time DEBUG_INFORMATION_FORMAT=dwarf COMPILER_INDEX_STORE_ENABLE=NO", 12 | "typescript": "tsc --noEmit", 13 | "test": "jest" 14 | }, 15 | "dependencies": { 16 | "react": "^18.3.1", 17 | "react-native": "^0.77.1" 18 | }, 19 | "devDependencies": { 20 | "@babel/core": "^7.25.8", 21 | "@babel/preset-env": "^7.25.8", 22 | "@babel/runtime": "^7.25.7", 23 | "@react-native-community/cli": "15.0.1", 24 | "@react-native-community/cli-platform-android": "15.0.1", 25 | "@react-native-community/cli-platform-ios": "15.0.1", 26 | "@react-native/babel-preset": "0.77.1", 27 | "@react-native/eslint-config": "0.77.1", 28 | "@react-native/metro-config": "0.77.1", 29 | "@react-native/typescript-config": "0.77.1", 30 | "@types/jest": "^29.5.13", 31 | "babel-plugin-module-resolver": "^5.0.2", 32 | "jest": "^29.3.1" 33 | }, 34 | "jest": { 35 | "preset": "react-native" 36 | }, 37 | "engines": { 38 | "node": ">=20" 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /package/example/react-native.config.js: -------------------------------------------------------------------------------- 1 | const path = require('path'); 2 | const pak = require('../package.json'); 3 | 4 | module.exports = { 5 | dependencies: { 6 | [pak.name]: { 7 | root: path.join(__dirname, '..'), 8 | }, 9 | }, 10 | }; 11 | -------------------------------------------------------------------------------- /package/example/src/App.tsx: -------------------------------------------------------------------------------- 1 | import * as React from 'react'; 2 | 3 | import { StyleSheet, View, TextInput, Alert, Button, Text } from 'react-native'; 4 | import { MMKV, useMMKVListener, useMMKVString } from 'react-native-mmkv'; 5 | 6 | const storage = new MMKV(); 7 | 8 | export default function App() { 9 | const [text, setText] = React.useState(''); 10 | const [key, setKey] = React.useState(''); 11 | const [keys, setKeys] = React.useState([]); 12 | 13 | const [example, setExample] = useMMKVString('yeeeet'); 14 | 15 | useMMKVListener((k) => { 16 | console.log(`${k} changed! New size: ${storage.size}`); 17 | }); 18 | 19 | const save = React.useCallback(() => { 20 | if (key == null || key.length < 1) { 21 | Alert.alert('Empty key!', 'Enter a key first.'); 22 | return; 23 | } 24 | try { 25 | console.log('setting...'); 26 | storage.set(key, text); 27 | console.log('set.'); 28 | } catch (e) { 29 | console.error('Error:', e); 30 | Alert.alert('Failed to set value for key "test"!', JSON.stringify(e)); 31 | } 32 | }, [key, text]); 33 | const read = React.useCallback(() => { 34 | if (key == null || key.length < 1) { 35 | Alert.alert('Empty key!', 'Enter a key first.'); 36 | return; 37 | } 38 | try { 39 | console.log('getting...'); 40 | const value = storage.getString(key); 41 | console.log('got:', value); 42 | Alert.alert('Result', `"${key}" = "${value}"`); 43 | } catch (e) { 44 | console.error('Error:', e); 45 | Alert.alert('Failed to get value for key "test"!', JSON.stringify(e)); 46 | } 47 | }, [key]); 48 | 49 | React.useEffect(() => { 50 | try { 51 | console.log('getting all keys...'); 52 | const _keys = storage.getAllKeys(); 53 | setKeys(_keys); 54 | console.log('MMKV keys:', _keys); 55 | } catch (e) { 56 | console.error('Error:', e); 57 | } 58 | }, []); 59 | 60 | React.useEffect(() => { 61 | console.log(`Value of useMMKVString: ${example}`); 62 | const interval = setInterval(() => { 63 | setExample((val) => { 64 | return val === 'yeeeet' ? undefined : 'yeeeet'; 65 | }); 66 | }, 1000); 67 | return () => { 68 | clearInterval(interval); 69 | }; 70 | }, [example, setExample]); 71 | 72 | return ( 73 | 74 | Available Keys: {keys.join(', ')} 75 | 76 | Key: 77 | 83 | 84 | 85 | Value: 86 | 92 | 93 |