├── .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 |
6 |
7 |
8 |
9 |
10 |
MMKV
11 | The fastest key/value storage for React Native.
12 |
13 |
14 |
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 | storage.ts
8 |
9 |
10 |
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 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 | App.tsx
69 |
70 |
71 |
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 |
113 |
114 |
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 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
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 |
94 |
95 |
96 | );
97 | }
98 |
99 | const styles = StyleSheet.create({
100 | container: {
101 | flex: 1,
102 | alignItems: 'center',
103 | justifyContent: 'center',
104 | paddingHorizontal: 20,
105 | },
106 | keys: {
107 | fontSize: 14,
108 | color: 'grey',
109 | },
110 | title: {
111 | fontSize: 16,
112 | color: 'black',
113 | marginRight: 10,
114 | },
115 | row: {
116 | flexDirection: 'row',
117 | alignItems: 'center',
118 | },
119 | textInput: {
120 | flex: 1,
121 | marginVertical: 20,
122 | borderWidth: StyleSheet.hairlineWidth,
123 | borderColor: 'black',
124 | borderRadius: 5,
125 | padding: 10,
126 | },
127 | });
128 |
--------------------------------------------------------------------------------
/package/example/test/MMKV.test.ts:
--------------------------------------------------------------------------------
1 | import { MMKV } from 'react-native-mmkv';
2 |
3 | describe('Example test', () => {
4 | let storage: MMKV;
5 |
6 | beforeAll(() => {
7 | storage = new MMKV();
8 | });
9 |
10 | it('functions correctly', () => {
11 | storage.set('testString', 'value');
12 | storage.set('testNumber', 99);
13 | storage.set('testBoolean', false);
14 |
15 | expect(storage.getString('testString')).toStrictEqual('value');
16 | expect(storage.getNumber('testString')).toBeUndefined();
17 | expect(storage.getBoolean('testString')).toBeUndefined();
18 | expect(storage.getString('testNumber')).toBeUndefined();
19 | expect(storage.getNumber('testNumber')).toStrictEqual(99);
20 | expect(storage.getBoolean('testNumber')).toBeUndefined();
21 | expect(storage.getString('testBoolean')).toBeUndefined();
22 | expect(storage.getNumber('testBoolean')).toBeUndefined();
23 | expect(storage.getBoolean('testBoolean')).toStrictEqual(false);
24 | expect(storage.getAllKeys()).toEqual(
25 | expect.arrayContaining(['testString', 'testNumber', 'testBoolean'])
26 | );
27 |
28 | storage.delete('testBoolean');
29 | expect(storage.contains('testBoolean')).toBeFalsy();
30 | expect(storage.getAllKeys()).toEqual(
31 | expect.arrayContaining(['testString', 'testNumber'])
32 | );
33 |
34 | storage.clearAll();
35 | expect(storage.toString()).toStrictEqual('MMKV (mmkv.default): []');
36 | });
37 | });
38 |
--------------------------------------------------------------------------------
/package/example/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "../tsconfig",
3 | "include": ["src/**/*", "test/**/*"],
4 | "compilerOptions": {
5 | "paths": {
6 | "react-native-mmkv": ["../src/index"]
7 | }
8 | },
9 | "exclude": [
10 | "node_modules"
11 | ]
12 | }
13 |
--------------------------------------------------------------------------------
/package/img/banner-dark.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mrousavy/react-native-mmkv/fefb2db7e8bd281998a38cb0a65704455c443446/package/img/banner-dark.png
--------------------------------------------------------------------------------
/package/img/banner-light.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mrousavy/react-native-mmkv/fefb2db7e8bd281998a38cb0a65704455c443446/package/img/banner-light.png
--------------------------------------------------------------------------------
/package/img/benchmark_1000_get.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mrousavy/react-native-mmkv/fefb2db7e8bd281998a38cb0a65704455c443446/package/img/benchmark_1000_get.png
--------------------------------------------------------------------------------
/package/ios/AppleLogger.mm:
--------------------------------------------------------------------------------
1 | //
2 | // AppleMmkvLogger.m
3 | // react-native-mmkv
4 | //
5 | // Created by Marc Rousavy on 25.03.24.
6 | //
7 |
8 | #import "MmkvLogger.h"
9 | #import
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 | NSLog(@"[%s]: %s", tag.c_str(), message.c_str());
15 | #pragma clang diagnostic pop
16 | }
17 |
--------------------------------------------------------------------------------
/package/ios/MmkvOnLoad.mm:
--------------------------------------------------------------------------------
1 | //
2 | // MmkvOnLoad.mm
3 | // react-native-mmkv
4 | //
5 | // Created by Marc Rousavy on 27.03.24.
6 | //
7 |
8 | #import "NativeMmkvModule.h"
9 | #import
10 | #import
11 |
12 | @interface MMKVOnLoad : NSObject
13 | @end
14 |
15 | @implementation MMKVOnLoad
16 |
17 | + (void)load {
18 | facebook::react::registerCxxModuleToGlobalModuleMap(
19 | std::string(facebook::react::NativeMmkvModule::kModuleName),
20 | [&](std::shared_ptr jsInvoker) {
21 | return std::make_shared(jsInvoker);
22 | });
23 | }
24 |
25 | @end
26 |
--------------------------------------------------------------------------------
/package/ios/MmkvPlatformContext.h:
--------------------------------------------------------------------------------
1 | //
2 | // RTNMmkvPlatformContext.h
3 | // Pods
4 | //
5 | // Created by Marc Rousavy on 27.03.24.
6 | //
7 |
8 | #pragma once
9 |
10 | #import
11 | #import
12 |
13 | NS_ASSUME_NONNULL_BEGIN
14 |
15 | @interface MmkvPlatformContext : NSObject
16 |
17 | @end
18 |
19 | NS_ASSUME_NONNULL_END
20 |
--------------------------------------------------------------------------------
/package/ios/MmkvPlatformContextModule.mm:
--------------------------------------------------------------------------------
1 | //
2 | // AppleMmkvPlatformContext.m
3 | // react-native-mmkv
4 | //
5 | // Created by Marc Rousavy on 25.03.24.
6 | //
7 |
8 | #import "MmkvPlatformContext.h"
9 | #import
10 |
11 | @implementation MmkvPlatformContext
12 |
13 | RCT_EXPORT_MODULE()
14 |
15 | - (std::shared_ptr)getTurboModule:
16 | (const facebook::react::ObjCTurboModule::InitParams&)params {
17 | return std::make_shared(params);
18 | }
19 |
20 | - (NSString*)getBaseDirectory {
21 | #if TARGET_OS_TV
22 | NSArray* paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
23 | #else
24 | NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
25 | #endif
26 | NSString* documentPath = (NSString*)[paths firstObject];
27 | if (documentPath.length > 0) {
28 | NSString* basePath = [documentPath stringByAppendingPathComponent:@"mmkv"];
29 | return basePath;
30 | } else {
31 | @throw [NSException exceptionWithName:@"BasePathNotFound"
32 | reason:@"Cannot find base-path to store MMKV files!"
33 | userInfo:nil];
34 | }
35 | }
36 |
37 | - (NSString*)getAppGroupDirectory {
38 | NSString* appGroup = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"AppGroup"];
39 | if (appGroup == nil) {
40 | // No AppGroup set in Info.plist.
41 | return nil;
42 | }
43 | NSURL* groupDir =
44 | [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:appGroup];
45 | if (groupDir == nil) {
46 | // We have an AppGroup set in Info.plist, but the path is not readable!
47 | @throw [NSException exceptionWithName:@"AppGroupNotAccessible"
48 | reason:@"An AppGroup was set in Info.plist, but it is not "
49 | @"accessible via NSFileManager!"
50 | userInfo:@{@"appGroup" : appGroup}];
51 | }
52 | return groupDir.path;
53 | }
54 |
55 | @end
56 |
--------------------------------------------------------------------------------
/package/lefthook.yml:
--------------------------------------------------------------------------------
1 | pre-commit:
2 | parallel: true
3 | commands:
4 | lint:
5 | glob: "*.{js,ts,jsx,tsx}"
6 | run: npx eslint {staged_files}
7 | types:
8 | glob: "*.{js,ts, jsx, tsx}"
9 | run: npx tsc --noEmit
10 | commit-msg:
11 | parallel: true
12 | commands:
13 | commitlint:
14 | run: npx commitlint --edit
15 |
--------------------------------------------------------------------------------
/package/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "react-native-mmkv",
3 | "version": "3.2.0",
4 | "description": "The fastest key/value storage for React Native. ~30x faster than AsyncStorage! Works on Android, iOS and Web.",
5 | "main": "lib/commonjs/index",
6 | "module": "lib/module/index",
7 | "types": "lib/typescript/src/index.d.ts",
8 | "react-native": "src/index",
9 | "source": "src/index",
10 | "files": [
11 | "cpp/**/*.h",
12 | "cpp/**/*.cpp",
13 | "MMKV/Core",
14 | "android/src",
15 | "android/build.gradle",
16 | "android/CMakeLists.txt",
17 | "android/cpp-adapter.cpp",
18 | "android/gradle.properties",
19 | "lib/commonjs",
20 | "lib/module",
21 | "lib/typescript",
22 | "ios/**/*.h",
23 | "ios/**/*.m",
24 | "ios/**/*.mm",
25 | "ios/**/*.cpp",
26 | "src",
27 | "react-native-mmkv.podspec",
28 | "react-native.config.js",
29 | "README.md"
30 | ],
31 | "scripts": {
32 | "typescript": "tsc --noEmit",
33 | "lint": "eslint \"**/*.{js,ts,tsx}\"",
34 | "lint-ci": "yarn lint -f ./node_modules/@firmnav/eslint-github-actions-formatter/dist/formatter.js",
35 | "lint-cpp": "scripts/clang-format.sh",
36 | "check-all": "yarn lint --fix && yarn lint-cpp",
37 | "test": "jest",
38 | "typecheck": "tsc --noEmit",
39 | "clean": "del-cli android/build example/android/build example/android/app/build example/ios/build lib",
40 | "prepare": "git submodule update --init --recursive && bob build",
41 | "prepack": "bob build",
42 | "update-submodule": "git submodule update --remote --merge",
43 | "pods": "cd example && yarn pods",
44 | "release": "release-it",
45 | "codegen": "npx react-native codegen"
46 | },
47 | "keywords": [
48 | "react-native",
49 | "ios",
50 | "android",
51 | "mmkv",
52 | "storage",
53 | "key",
54 | "value",
55 | "fast",
56 | "turbo",
57 | "async"
58 | ],
59 | "repository": {
60 | "type": "git",
61 | "url": "git+https://github.com/mrousavy/react-native-mmkv.git"
62 | },
63 | "author": "Marc Rousavy (https://github.com/mrousavy)",
64 | "license": "(MIT AND BSD-3-Clause)",
65 | "bugs": {
66 | "url": "https://github.com/mrousavy/react-native-mmkv/issues"
67 | },
68 | "homepage": "https://github.com/mrousavy/react-native-mmkv#readme",
69 | "publishConfig": {
70 | "registry": "https://registry.npmjs.org/"
71 | },
72 | "devDependencies": {
73 | "@firmnav/eslint-github-actions-formatter": "^1.0.1",
74 | "@jamesacarr/eslint-formatter-github-actions": "^0.2.0",
75 | "@react-native-community/cli-types": "^15.1.3",
76 | "@react-native/eslint-config": "^0.77.1",
77 | "@release-it/conventional-changelog": "^9.0.1",
78 | "@testing-library/react-native": "^13.0.1",
79 | "@types/jest": "^29.5.13",
80 | "@types/react": "^18.3.11",
81 | "del-cli": "^6.0.0",
82 | "eslint": "^8.51.0",
83 | "eslint-config-prettier": "^9.0.0",
84 | "eslint-plugin-prettier": "^5.2.1",
85 | "jest": "^29.7.0",
86 | "prettier": "^3.3.3",
87 | "react": "^18.3.1",
88 | "react-native": "^0.77.1",
89 | "react-native-builder-bob": "^0.37.0",
90 | "react-test-renderer": "18.3.1",
91 | "release-it": "^17.10.0",
92 | "typescript": "^5.5.4"
93 | },
94 | "peerDependencies": {
95 | "react": "*",
96 | "react-native": "*"
97 | },
98 | "jest": {
99 | "preset": "react-native",
100 | "modulePathIgnorePatterns": [
101 | "/example/node_modules",
102 | "/lib/"
103 | ]
104 | },
105 | "release-it": {
106 | "git": {
107 | "commitMessage": "chore: release ${version}",
108 | "tagName": "v${version}"
109 | },
110 | "npm": {
111 | "publish": true
112 | },
113 | "github": {
114 | "release": true
115 | },
116 | "plugins": {
117 | "@release-it/conventional-changelog": {
118 | "preset": {
119 | "name": "conventionalcommits",
120 | "types": [
121 | {
122 | "type": "feat",
123 | "section": "✨ Features"
124 | },
125 | {
126 | "type": "fix",
127 | "section": "🐛 Bug Fixes"
128 | },
129 | {
130 | "type": "perf",
131 | "section": "💨 Performance Improvements"
132 | },
133 | {
134 | "type": "chore(deps)",
135 | "section": "🛠️ Dependency Upgrades"
136 | },
137 | {
138 | "type": "docs",
139 | "section": "📚 Documentation"
140 | }
141 | ]
142 | }
143 | }
144 | }
145 | },
146 | "eslintIgnore": [
147 | "node_modules/",
148 | "lib/",
149 | "MMKV"
150 | ],
151 | "prettier": {
152 | "quoteProps": "consistent",
153 | "singleQuote": true,
154 | "tabWidth": 2,
155 | "trailingComma": "es5",
156 | "useTabs": false
157 | },
158 | "react-native-builder-bob": {
159 | "source": "src",
160 | "output": "lib",
161 | "targets": [
162 | "commonjs",
163 | "module",
164 | [
165 | "typescript",
166 | {
167 | "project": "tsconfig.json"
168 | }
169 | ]
170 | ]
171 | },
172 | "codegenConfig": {
173 | "name": "RNMmkvSpec",
174 | "type": "modules",
175 | "jsSrcsDir": "src"
176 | },
177 | "packageManager": "yarn@1.22.19+sha1.4ba7fc5c6e704fce2066ecbfb0b0d8976fe62447"
178 | }
179 |
--------------------------------------------------------------------------------
/package/react-native-mmkv.podspec:
--------------------------------------------------------------------------------
1 | require "json"
2 |
3 | package = JSON.parse(File.read(File.join(__dir__, "package.json")))
4 | folly_compiler_flags = '-DFOLLY_NO_CONFIG -DFOLLY_MOBILE=1 -DFOLLY_USE_LIBCPP=1 -Wno-comma -Wno-shorten-64-to-32'
5 |
6 | Pod::UI.puts "[react-native-mmkv] Thank you for using react-native-mmkv ❤️"
7 | Pod::UI.puts "[react-native-mmkv] If you enjoy using react-native-mmkv, please consider sponsoring this project: https://github.com/sponsors/mrousavy"
8 |
9 | Pod::Spec.new do |s|
10 | s.name = "react-native-mmkv"
11 | s.version = package["version"]
12 | s.summary = package["description"]
13 | s.homepage = package["homepage"]
14 | s.license = package["license"]
15 | s.authors = package["author"]
16 |
17 | s.platforms = { :ios => min_ios_version_supported, :tvos => "12.0", :osx => "10.14" }
18 | s.source = { :git => "https://github.com/mrousavy/react-native-mmkv.git", :tag => "#{s.version}" }
19 |
20 | s.pod_target_xcconfig = {
21 | "CLANG_CXX_LANGUAGE_STANDARD" => "c++17",
22 | "CLANG_CXX_LIBRARY" => "libc++",
23 | "CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF" => "NO",
24 | # FORCE_POSIX ensures we are using C++ types instead of Objective-C types for MMKV.
25 | "GCC_PREPROCESSOR_DEFINITIONS" => "$(inherited) FORCE_POSIX",
26 | }
27 | s.compiler_flags = '-x objective-c++'
28 | s.libraries = "z", "c++"
29 | s.source_files = [
30 | # react-native-mmkv
31 | "ios/**/*.{h,m,mm}",
32 | "cpp/**/*.{hpp,cpp,c,h}",
33 | # MMKV/Core
34 | "MMKV/Core/**/*.{h,cpp,hpp,S}",
35 | ]
36 |
37 | install_modules_dependencies(s)
38 | end
39 |
--------------------------------------------------------------------------------
/package/react-native.config.js:
--------------------------------------------------------------------------------
1 | // https://github.com/react-native-community/cli/blob/main/docs/dependencies.md
2 |
3 | module.exports = {
4 | dependency: {
5 | platforms: {
6 | /**
7 | * @type {import('@react-native-community/cli-types').IOSDependencyParams}
8 | */
9 | ios: {},
10 | /**
11 | * @type {import('@react-native-community/cli-types').AndroidDependencyParams}
12 | */
13 | android: {
14 | cxxModuleCMakeListsModuleName: 'react-native-mmkv',
15 | cxxModuleCMakeListsPath: 'CMakeLists.txt',
16 | cxxModuleHeaderName: 'NativeMmkvModule',
17 | },
18 | },
19 | },
20 | };
21 |
--------------------------------------------------------------------------------
/package/scripts/clang-format.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | if which clang-format >/dev/null; then
4 | find cpp ios android/src/main/cpp -type f \( -name "*.h" -o -name "*.cpp" -o -name "*.m" -o -name "*.mm" \) -print0 | while read -d $'\0' file; do
5 | echo "-> cpp-lint $file"
6 | clang-format -i "$file"
7 | done
8 | else
9 | echo "warning: clang-format not installed, download from https://clang.llvm.org/docs/ClangFormat.html (or run brew install clang-format)"
10 | fi
11 |
--------------------------------------------------------------------------------
/package/src/MMKV.ts:
--------------------------------------------------------------------------------
1 | import { createMMKV } from './createMMKV';
2 | import { createMockMMKV } from './createMMKV.mock';
3 | import { isTest } from './PlatformChecker';
4 | import type {
5 | Configuration,
6 | Listener,
7 | MMKVInterface,
8 | NativeMMKV,
9 | } from './Types';
10 | import { addMemoryWarningListener } from './MemoryWarningListener';
11 |
12 | const onValueChangedListeners = new Map void)[]>();
13 |
14 | /**
15 | * A single MMKV instance.
16 | */
17 | export class MMKV implements MMKVInterface {
18 | private nativeInstance: NativeMMKV;
19 | private functionCache: Partial;
20 | private id: string;
21 |
22 | /**
23 | * Creates a new MMKV instance with the given Configuration.
24 | * If no custom `id` is supplied, `'mmkv.default'` will be used.
25 | */
26 | constructor(configuration: Configuration = { id: 'mmkv.default' }) {
27 | this.id = configuration.id;
28 | this.nativeInstance = isTest()
29 | ? createMockMMKV()
30 | : createMMKV(configuration);
31 | this.functionCache = {};
32 |
33 | addMemoryWarningListener(this);
34 | }
35 |
36 | private get onValueChangedListeners() {
37 | if (!onValueChangedListeners.has(this.id)) {
38 | onValueChangedListeners.set(this.id, []);
39 | }
40 | return onValueChangedListeners.get(this.id)!;
41 | }
42 |
43 | private getFunctionFromCache(
44 | functionName: T
45 | ): NativeMMKV[T] {
46 | if (this.functionCache[functionName] == null) {
47 | this.functionCache[functionName] = this.nativeInstance[functionName];
48 | }
49 | return this.functionCache[functionName] as NativeMMKV[T];
50 | }
51 |
52 | private onValuesChanged(keys: string[]) {
53 | if (this.onValueChangedListeners.length === 0) return;
54 |
55 | for (const key of keys) {
56 | for (const listener of this.onValueChangedListeners) {
57 | listener(key);
58 | }
59 | }
60 | }
61 |
62 | get size(): number {
63 | return this.nativeInstance.size;
64 | }
65 | get isReadOnly(): boolean {
66 | return this.nativeInstance.isReadOnly;
67 | }
68 | set(key: string, value: boolean | string | number | ArrayBuffer): void {
69 | const func = this.getFunctionFromCache('set');
70 | func(key, value);
71 |
72 | this.onValuesChanged([key]);
73 | }
74 | getBoolean(key: string): boolean | undefined {
75 | const func = this.getFunctionFromCache('getBoolean');
76 | return func(key);
77 | }
78 | getString(key: string): string | undefined {
79 | const func = this.getFunctionFromCache('getString');
80 | return func(key);
81 | }
82 | getNumber(key: string): number | undefined {
83 | const func = this.getFunctionFromCache('getNumber');
84 | return func(key);
85 | }
86 | getBuffer(key: string): ArrayBufferLike | undefined {
87 | const func = this.getFunctionFromCache('getBuffer');
88 | return func(key);
89 | }
90 | contains(key: string): boolean {
91 | const func = this.getFunctionFromCache('contains');
92 | return func(key);
93 | }
94 | delete(key: string): void {
95 | const func = this.getFunctionFromCache('delete');
96 | func(key);
97 |
98 | this.onValuesChanged([key]);
99 | }
100 | getAllKeys(): string[] {
101 | const func = this.getFunctionFromCache('getAllKeys');
102 | return func();
103 | }
104 | clearAll(): void {
105 | const keys = this.getAllKeys();
106 |
107 | const func = this.getFunctionFromCache('clearAll');
108 | func();
109 |
110 | this.onValuesChanged(keys);
111 | }
112 | recrypt(key: string | undefined): void {
113 | const func = this.getFunctionFromCache('recrypt');
114 | return func(key);
115 | }
116 | trim(): void {
117 | const func = this.getFunctionFromCache('trim');
118 | func();
119 | }
120 |
121 | toString(): string {
122 | return `MMKV (${this.id}): [${this.getAllKeys().join(', ')}]`;
123 | }
124 | toJSON(): object {
125 | return {
126 | [this.id]: this.getAllKeys(),
127 | };
128 | }
129 |
130 | addOnValueChangedListener(onValueChanged: (key: string) => void): Listener {
131 | this.onValueChangedListeners.push(onValueChanged);
132 |
133 | return {
134 | remove: () => {
135 | const index = this.onValueChangedListeners.indexOf(onValueChanged);
136 | if (index !== -1) {
137 | this.onValueChangedListeners.splice(index, 1);
138 | }
139 | },
140 | };
141 | }
142 | }
143 |
--------------------------------------------------------------------------------
/package/src/MemoryWarningListener.ts:
--------------------------------------------------------------------------------
1 | import { AppState } from 'react-native';
2 | import type { NativeEventSubscription } from 'react-native';
3 | import { MMKVInterface } from './Types';
4 |
5 | export function addMemoryWarningListener(mmkv: MMKVInterface): void {
6 | if (global.WeakRef != null && global.FinalizationRegistry != null) {
7 | // 1. Weakify MMKV so we can safely use it inside the memoryWarning event listener
8 | const weakMmkv = new WeakRef(mmkv);
9 | const listener = AppState.addEventListener('memoryWarning', () => {
10 | // 0. Everytime we receive a memoryWarning, we try to trim the MMKV instance (if it is still valid)
11 | weakMmkv.deref()?.trim();
12 | });
13 | // 2. Add a listener to when the MMKV instance is deleted
14 | const finalization = new FinalizationRegistry(
15 | (l: NativeEventSubscription) => {
16 | // 3. When MMKV is deleted, this listener will be called with the memoryWarning listener.
17 | l.remove();
18 | }
19 | );
20 | // 2.1. Bind the listener to the actual MMKV instance.
21 | finalization.register(mmkv, listener);
22 | } else {
23 | // WeakRef/FinalizationRegistry is not implemented in this engine.
24 | // Just add the listener, even if it retains MMKV strong forever.
25 | AppState.addEventListener('memoryWarning', () => {
26 | mmkv.trim();
27 | });
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/package/src/MemoryWarningListener.web.ts:
--------------------------------------------------------------------------------
1 | import { MMKVInterface } from './Types';
2 |
3 | export const addMemoryWarningListener = (_mmkv: MMKVInterface): void => {
4 | //no-op function, there is not a web equivalent to memory warning
5 | };
6 |
--------------------------------------------------------------------------------
/package/src/ModuleNotFoundError.ts:
--------------------------------------------------------------------------------
1 | import { NativeModules, Platform } from 'react-native';
2 |
3 | declare global {
4 | // A react-native internal from TurboModuleRegistry.js
5 | var __turboModuleProxy: unknown | undefined;
6 | }
7 |
8 | const BULLET_POINT = '\n* ';
9 |
10 | function messageWithSuggestions(
11 | message: string,
12 | suggestions: string[]
13 | ): string {
14 | return message + BULLET_POINT + suggestions.join(BULLET_POINT);
15 | }
16 |
17 | function getFrameworkType(): 'react-native' | 'expo' | 'expo-go' {
18 | // check if Expo
19 | const ExpoConstants =
20 | NativeModules.NativeUnimoduleProxy?.modulesConstants?.ExponentConstants;
21 | if (ExpoConstants != null) {
22 | if (ExpoConstants.appOwnership === 'expo') {
23 | // We're running Expo Go
24 | return 'expo-go';
25 | } else {
26 | // We're running Expo bare / standalone
27 | return 'expo';
28 | }
29 | }
30 | return 'react-native';
31 | }
32 |
33 | export class ModuleNotFoundError extends Error {
34 | constructor(cause?: unknown) {
35 | // TurboModule not found, something went wrong!
36 | if (global.__turboModuleProxy == null) {
37 | // TurboModules are not available/new arch is not enabled.
38 | // react-native-mmkv 3.x.x requires new arch (react-native >0.74)
39 | // react-native-mmkv 2.x.x works on old arch (react-native <0.74)
40 | const message =
41 | 'Failed to create a new MMKV instance: react-native-mmkv 3.x.x requires TurboModules, but the new architecture is not enabled!';
42 | const suggestions: string[] = [];
43 | suggestions.push(
44 | 'Downgrade to react-native-mmkv 2.x.x if you want to stay on the old architecture.'
45 | );
46 | suggestions.push(
47 | 'Enable the new architecture in your app to use react-native-mmkv 3.x.x. (See https://github.com/reactwg/react-native-new-architecture/blob/main/docs/enable-apps.md)'
48 | );
49 | const error = messageWithSuggestions(message, suggestions);
50 | super(error, { cause: cause });
51 | return;
52 | }
53 |
54 | const framework = getFrameworkType();
55 | if (framework === 'expo-go') {
56 | super(
57 | 'react-native-mmkv is not supported in Expo Go! Use EAS (`expo prebuild`) or eject to a bare workflow instead.'
58 | );
59 | return;
60 | }
61 |
62 | const message =
63 | 'Failed to create a new MMKV instance: The native MMKV Module could not be found.';
64 | const suggestions: string[] = [];
65 | suggestions.push(
66 | 'Make sure react-native-mmkv is correctly autolinked (run `npx react-native config` to verify)'
67 | );
68 | suggestions.push(
69 | 'Make sure you enabled the new architecture (TurboModules) and CodeGen properly generated the react-native-mmkv specs. See https://github.com/reactwg/react-native-new-architecture/blob/main/docs/enable-apps.md'
70 | );
71 | suggestions.push(
72 | 'Make sure you are using react-native 0.74.0 or higher, because react-native-mmkv is a C++ TurboModule.'
73 | );
74 | suggestions.push('Make sure you rebuilt the app.');
75 | if (framework === 'expo') {
76 | suggestions.push('Make sure you ran `expo prebuild`.');
77 | }
78 | switch (Platform.OS) {
79 | case 'ios':
80 | case 'macos':
81 | suggestions.push(
82 | 'Make sure you ran `pod install` in the ios/ directory.'
83 | );
84 | break;
85 | case 'android':
86 | suggestions.push('Make sure gradle is synced.');
87 | break;
88 | default:
89 | throw new Error(`MMKV is not supported on ${Platform.OS}!`);
90 | }
91 |
92 | const error = messageWithSuggestions(message, suggestions);
93 | super(error, { cause: cause });
94 | }
95 | }
96 |
--------------------------------------------------------------------------------
/package/src/NativeMmkv.ts:
--------------------------------------------------------------------------------
1 | import type { TurboModule } from 'react-native';
2 | import { TurboModuleRegistry } from 'react-native';
3 | import type { UnsafeObject } from 'react-native/Libraries/Types/CodegenTypes';
4 | import { ModuleNotFoundError } from './ModuleNotFoundError';
5 | import { getMMKVPlatformContextTurboModule } from './NativeMmkvPlatformContext';
6 |
7 | /**
8 | * IMPORTANT: These types are also in the Types.ts file.
9 | * Due to how react-native-codegen works these are required here as the spec types can not be separated from spec.
10 | * We also need the types separate to allow bypassing importing turbo module registry in web
11 | */
12 | /**
13 | * Configures the mode of the MMKV instance.
14 | */
15 | export enum Mode {
16 | /**
17 | * The MMKV instance is only used from a single process (this app).
18 | */
19 | SINGLE_PROCESS,
20 | /**
21 | * The MMKV instance may be used from multiple processes, such as app clips, share extensions or background services.
22 | */
23 | MULTI_PROCESS,
24 | }
25 |
26 | /**
27 | * Used for configuration of a single MMKV instance.
28 | */
29 | export interface Configuration {
30 | /**
31 | * The MMKV instance's ID. If you want to use multiple instances, make sure to use different IDs!
32 | *
33 | * @example
34 | * ```ts
35 | * const userStorage = new MMKV({ id: `user-${userId}-storage` })
36 | * const globalStorage = new MMKV({ id: 'global-app-storage' })
37 | * ```
38 | *
39 | * @default 'mmkv.default'
40 | */
41 | id: string;
42 | /**
43 | * The MMKV instance's root path. By default, MMKV stores file inside `$(Documents)/mmkv/`. You can customize MMKV's root directory on MMKV initialization:
44 |
45 | * @example
46 | * ```ts
47 | * const temporaryStorage = new MMKV({ path: '/tmp/' })
48 | * ```
49 | *
50 | * @note On iOS, if an `AppGroup` is set in `Info.plist` and `path` is `undefined`, MMKV will use the `AppGroup` directory.
51 | * App Groups allow you to share MMKV storage between apps, widgets and extensions within the same AppGroup bundle.
52 | * For more information, see [the `Configuration` section](https://github.com/Tencent/MMKV/wiki/iOS_tutorial#configuration).
53 | *
54 | * @default undefined
55 | */
56 | path?: string;
57 | /**
58 | * The MMKV instance's encryption/decryption key. By default, MMKV stores all key-values in plain text on file, relying on iOS's sandbox to make sure the file is encrypted. Should you worry about information leaking, you can choose to encrypt MMKV.
59 | *
60 | * Encryption keys can have a maximum length of 16 bytes.
61 | *
62 | * @example
63 | * ```ts
64 | * const secureStorage = new MMKV({ encryptionKey: 'my-encryption-key!' })
65 | * ```
66 | *
67 | * @default undefined
68 | */
69 | encryptionKey?: string;
70 | /**
71 | * Configure the processing mode for MMKV.
72 | * - `SINGLE_PROCESS`: The MMKV instance is only used from a single process (this app).
73 | * - `MULTI_PROCESS`: The MMKV instance may be used from multiple processes, such as app clips, share extensions or background services.
74 | *
75 | * @default SINGLE_PROCESS
76 | */
77 | mode?: Mode;
78 | /**
79 | * If `true`, the MMKV instance can only read from the storage, but not write to it.
80 | */
81 | readOnly?: boolean;
82 | }
83 |
84 | export interface Spec extends TurboModule {
85 | /**
86 | * Initialize MMKV with the given base storage directory.
87 | * This should be the documents directory by default.
88 | */
89 | initialize(basePath: string): boolean;
90 | /**
91 | * Create a new instance of MMKV.
92 | * The returned {@linkcode UnsafeObject} is a `jsi::HostObject`.
93 | */
94 | createMMKV(configuration: Configuration): UnsafeObject;
95 | }
96 |
97 | let mmkvModule: Spec | null;
98 |
99 | export function getMMKVTurboModule(): Spec {
100 | try {
101 | if (mmkvModule == null) {
102 | // 1. Load MMKV TurboModule
103 | mmkvModule = TurboModuleRegistry.getEnforcing('MmkvCxx');
104 |
105 | // 2. Get the PlatformContext TurboModule as well
106 | const platformContext = getMMKVPlatformContextTurboModule();
107 |
108 | // 3. Initialize it with the documents directory from platform-specific context
109 | const basePath = platformContext.getBaseDirectory();
110 | mmkvModule.initialize(basePath);
111 | }
112 |
113 | return mmkvModule;
114 | } catch (cause) {
115 | // TurboModule could not be found!
116 | throw new ModuleNotFoundError(cause);
117 | }
118 | }
119 |
--------------------------------------------------------------------------------
/package/src/NativeMmkvPlatformContext.ts:
--------------------------------------------------------------------------------
1 | import type { TurboModule } from 'react-native';
2 | import { TurboModuleRegistry } from 'react-native';
3 | import { ModuleNotFoundError } from './ModuleNotFoundError';
4 |
5 | export interface Spec extends TurboModule {
6 | /**
7 | * Gets the base directory of the documents storage
8 | */
9 | getBaseDirectory(): string;
10 | /**
11 | * Get the App Group directory if it exists, or `undefined` otherwise.
12 | *
13 | * The App Group directory will be used instead of a custom path to use the same
14 | * MMKV instance between the iOS app, Widgets, and other companion apps.
15 | *
16 | * To set an App Group, add a `AppGroup` field to `Info.plist`
17 | *
18 | * @platform ios
19 | */
20 | getAppGroupDirectory(): string | undefined;
21 | }
22 |
23 | let mmkvPlatformModule: Spec | null;
24 |
25 | export function getMMKVPlatformContextTurboModule(): Spec {
26 | try {
27 | if (mmkvPlatformModule == null) {
28 | // 1. Get the TurboModule
29 | mmkvPlatformModule = TurboModuleRegistry.getEnforcing(
30 | 'MmkvPlatformContext'
31 | );
32 | }
33 | return mmkvPlatformModule;
34 | } catch (e) {
35 | // TurboModule could not be found!
36 | throw new ModuleNotFoundError(e);
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/package/src/PlatformChecker.ts:
--------------------------------------------------------------------------------
1 | export function isTest(): boolean {
2 | if (global.process == null) {
3 | // In a WebBrowser/Electron the `process` variable does not exist
4 | return false;
5 | }
6 | return (
7 | process.env.JEST_WORKER_ID != null || process.env.VITEST_WORKER_ID != null
8 | );
9 | }
10 |
--------------------------------------------------------------------------------
/package/src/Types.ts:
--------------------------------------------------------------------------------
1 | /**
2 | * IMPORTANT: Some of these types are also in the NativeMmkv.ts file.
3 | * Due to how react-native-codegen works these are required here as the spec types can not be separated from spec.
4 | * We also need the types separate to allow bypassing importing turbo module registry in web
5 | */
6 |
7 | /**
8 | * Configures the mode of the MMKV instance.
9 | */
10 | export enum Mode {
11 | /**
12 | * The MMKV instance is only used from a single process (this app).
13 | */
14 | SINGLE_PROCESS,
15 | /**
16 | * The MMKV instance may be used from multiple processes, such as app clips, share extensions or background services.
17 | */
18 | MULTI_PROCESS,
19 | }
20 |
21 | /**
22 | * Used for configuration of a single MMKV instance.
23 | */
24 | export interface Configuration {
25 | /**
26 | * The MMKV instance's ID. If you want to use multiple instances, make sure to use different IDs!
27 | *
28 | * @example
29 | * ```ts
30 | * const userStorage = new MMKV({ id: `user-${userId}-storage` })
31 | * const globalStorage = new MMKV({ id: 'global-app-storage' })
32 | * ```
33 | *
34 | * @default 'mmkv.default'
35 | */
36 | id: string;
37 | /**
38 | * The MMKV instance's root path. By default, MMKV stores file inside `$(Documents)/mmkv/`. You can customize MMKV's root directory on MMKV initialization:
39 |
40 | * @example
41 | * ```ts
42 | * const temporaryStorage = new MMKV({ path: '/tmp/' })
43 | * ```
44 | *
45 | * @note On iOS, if an `AppGroup` is set in `Info.plist` and `path` is `undefined`, MMKV will use the `AppGroup` directory.
46 | * App Groups allow you to share MMKV storage between apps, widgets and extensions within the same AppGroup bundle.
47 | * For more information, see [the `Configuration` section](https://github.com/Tencent/MMKV/wiki/iOS_tutorial#configuration).
48 | *
49 | * @default undefined
50 | */
51 | path?: string;
52 | /**
53 | * The MMKV instance's encryption/decryption key. By default, MMKV stores all key-values in plain text on file, relying on iOS's sandbox to make sure the file is encrypted. Should you worry about information leaking, you can choose to encrypt MMKV.
54 | *
55 | * Encryption keys can have a maximum length of 16 bytes.
56 | *
57 | * @example
58 | * ```ts
59 | * const secureStorage = new MMKV({ encryptionKey: 'my-encryption-key!' })
60 | * ```
61 | *
62 | * @default undefined
63 | */
64 | encryptionKey?: string;
65 | /**
66 | * Configure the processing mode for MMKV.
67 | * - `SINGLE_PROCESS`: The MMKV instance is only used from a single process (this app).
68 | * - `MULTI_PROCESS`: The MMKV instance may be used from multiple processes, such as app clips, share extensions or background services.
69 | *
70 | * @default SINGLE_PROCESS
71 | */
72 | mode?: Mode;
73 | /**
74 | * If `true`, the MMKV instance can only read from the storage, but not write to it.
75 | * This is more efficient if you do not need to write to it.
76 | * @default false
77 | */
78 | readOnly?: boolean;
79 | }
80 |
81 | /**
82 | * Represents a single MMKV instance.
83 | */
84 | export interface NativeMMKV {
85 | /**
86 | * Set a value for the given `key`.
87 | *
88 | * @throws an Error if the value cannot be set.
89 | */
90 | set: (key: string, value: boolean | string | number | ArrayBuffer) => void;
91 | /**
92 | * Get the boolean value for the given `key`, or `undefined` if it does not exist.
93 | *
94 | * @default undefined
95 | */
96 | getBoolean: (key: string) => boolean | undefined;
97 | /**
98 | * Get the string value for the given `key`, or `undefined` if it does not exist.
99 | *
100 | * @default undefined
101 | */
102 | getString: (key: string) => string | undefined;
103 | /**
104 | * Get the number value for the given `key`, or `undefined` if it does not exist.
105 | *
106 | * @default undefined
107 | */
108 | getNumber: (key: string) => number | undefined;
109 | /**
110 | * Get a raw buffer of unsigned 8-bit (0-255) data.
111 | *
112 | * @default undefined
113 | */
114 | getBuffer: (key: string) => ArrayBufferLike | undefined;
115 | /**
116 | * Checks whether the given `key` is being stored in this MMKV instance.
117 | */
118 | contains: (key: string) => boolean;
119 | /**
120 | * Delete the given `key`.
121 | */
122 | delete: (key: string) => void;
123 | /**
124 | * Get all keys.
125 | *
126 | * @default []
127 | */
128 | getAllKeys: () => string[];
129 | /**
130 | * Delete all keys.
131 | */
132 | clearAll: () => void;
133 | /**
134 | * Sets (or updates) the encryption-key to encrypt all data in this MMKV instance with.
135 | *
136 | * To remove encryption, pass `undefined` as a key.
137 | *
138 | * Encryption keys can have a maximum length of 16 bytes.
139 | *
140 | * @throws an Error if the instance cannot be recrypted.
141 | */
142 | recrypt: (key: string | undefined) => void;
143 | /**
144 | * Trims the storage space and clears memory cache.
145 | *
146 | * Since MMKV does not resize itself after deleting keys, you can call `trim()`
147 | * after deleting a bunch of keys to manually trim the memory- and
148 | * disk-file to reduce storage and memory usage.
149 | *
150 | * In most applications, this is not needed at all.
151 | */
152 | trim(): void;
153 | /**
154 | * Get the current total size of the storage, in bytes.
155 | */
156 | readonly size: number;
157 | /**
158 | * Returns whether this instance is in read-only mode or not.
159 | * If this is `true`, you can only use "get"-functions.
160 | */
161 | readonly isReadOnly: boolean;
162 | }
163 |
164 | export interface Listener {
165 | remove: () => void;
166 | }
167 |
168 | export interface MMKVInterface extends NativeMMKV {
169 | /**
170 | * Adds a value changed listener. The Listener will be called whenever any value
171 | * in this storage instance changes (set or delete).
172 | *
173 | * To unsubscribe from value changes, call `remove()` on the Listener.
174 | */
175 | addOnValueChangedListener: (
176 | onValueChanged: (key: string) => void
177 | ) => Listener;
178 | }
179 |
--------------------------------------------------------------------------------
/package/src/__tests__/hooks.test.tsx:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { Button, Text } from 'react-native';
3 | import {
4 | act,
5 | fireEvent,
6 | render,
7 | renderHook,
8 | screen,
9 | } from '@testing-library/react-native';
10 | import { MMKV, useMMKVNumber, useMMKVString } from '..';
11 |
12 | const mmkv = new MMKV();
13 |
14 | beforeEach(() => {
15 | mmkv.clearAll();
16 | mmkv.trim();
17 | });
18 |
19 | test('hooks update when the value is changed directly through the instance', () => {
20 | const { result } = renderHook(() => useMMKVString('string-key', mmkv));
21 |
22 | expect(result.current[0]).toBeUndefined();
23 |
24 | // First, make a "normal" change
25 | act(() => {
26 | result.current[1]('value 1');
27 | });
28 |
29 | expect(result.current[0]).toStrictEqual('value 1');
30 |
31 | // Now, make the change directly through the instance.
32 | act(() => {
33 | mmkv.set('string-key', 'value 2');
34 | });
35 | expect(result.current[0]).toStrictEqual('value 2');
36 | });
37 |
38 | test('functional updates to hooks', () => {
39 | const Component: React.FC = () => {
40 | const [state, setState] = React.useState(0);
41 | const [value, setValue] = useMMKVNumber('number-key', mmkv);
42 |
43 | return (
44 | <>
45 | {
49 | // Increment the state value twice, using the function form of useState.
50 | setState((current) => current + 1);
51 | setState((current) => current + 1);
52 |
53 | // Increment the MMKV value twice, using the same function form.
54 | setValue((current) => (current ?? 0) + 1);
55 | setValue((current) => (current ?? 0) + 1);
56 | }}
57 | />
58 | State: {state.toString()}
59 | MMKV: {(value ?? 0).toString()}
60 | >
61 | );
62 | };
63 |
64 | render( );
65 |
66 | const button = screen.getByTestId('button');
67 |
68 | // Why these assertions:
69 | // https://github.com/mrousavy/react-native-mmkv/issues/599
70 | fireEvent.press(button);
71 | expect(screen.getByTestId('state-value').children).toStrictEqual([
72 | 'State: ',
73 | '2',
74 | ]);
75 | expect(screen.getByTestId('mmkv-value').children).toStrictEqual([
76 | 'MMKV: ',
77 | '2',
78 | ]);
79 |
80 | fireEvent.press(button);
81 | expect(screen.getByTestId('state-value').children).toStrictEqual([
82 | 'State: ',
83 | '4',
84 | ]);
85 | expect(screen.getByTestId('mmkv-value').children).toStrictEqual([
86 | 'MMKV: ',
87 | '4',
88 | ]);
89 | });
90 |
--------------------------------------------------------------------------------
/package/src/createMMKV.mock.ts:
--------------------------------------------------------------------------------
1 | import type { NativeMMKV } from './Types';
2 |
3 | /* Mock MMKV instance for use in tests */
4 | export const createMockMMKV = (): NativeMMKV => {
5 | const storage = new Map();
6 |
7 | return {
8 | clearAll: () => storage.clear(),
9 | delete: (key) => storage.delete(key),
10 | set: (key, value) => storage.set(key, value),
11 | getString: (key) => {
12 | const result = storage.get(key);
13 | return typeof result === 'string' ? result : undefined;
14 | },
15 | getNumber: (key) => {
16 | const result = storage.get(key);
17 | return typeof result === 'number' ? result : undefined;
18 | },
19 | getBoolean: (key) => {
20 | const result = storage.get(key);
21 | return typeof result === 'boolean' ? result : undefined;
22 | },
23 | getBuffer: (key) => {
24 | const result = storage.get(key);
25 | return result instanceof ArrayBuffer ? result : undefined;
26 | },
27 | getAllKeys: () => Array.from(storage.keys()),
28 | contains: (key) => storage.has(key),
29 | recrypt: () => {
30 | console.warn('Encryption is not supported in mocked MMKV instances!');
31 | },
32 | size: 0,
33 | isReadOnly: false,
34 | trim: () => {
35 | // no-op
36 | },
37 | };
38 | };
39 |
--------------------------------------------------------------------------------
/package/src/createMMKV.ts:
--------------------------------------------------------------------------------
1 | import { Platform } from 'react-native';
2 | import { getMMKVTurboModule } from './NativeMmkv';
3 | import { type Configuration, Mode, type NativeMMKV } from './Types';
4 | import { getMMKVPlatformContextTurboModule } from './NativeMmkvPlatformContext';
5 |
6 | export const createMMKV = (config: Configuration): NativeMMKV => {
7 | const module = getMMKVTurboModule();
8 |
9 | if (Platform.OS === 'ios') {
10 | if (config.path == null) {
11 | try {
12 | // If no `path` was supplied, we check if an `AppGroup` was set in Info.plist
13 | const appGroupDirectory =
14 | getMMKVPlatformContextTurboModule().getAppGroupDirectory();
15 | if (appGroupDirectory != null) {
16 | // If we have an `AppGroup` in Info.plist, use that as a path.
17 | config.path = appGroupDirectory;
18 | }
19 | } catch (e) {
20 | // We cannot throw errors here because it is a sync C++ TurboModule func. idk why.
21 | console.error(e);
22 | }
23 | }
24 | }
25 |
26 | if (typeof config.mode === 'number') {
27 | // Code-gen expects enums to be strings. In TS, they might be numbers tho.
28 | // This sucks, so we need a workaround.
29 | // @ts-expect-error the native side actually expects a string.
30 | config.mode = Mode[config.mode];
31 | }
32 |
33 | const instance = module.createMMKV(config);
34 | if (__DEV__) {
35 | if (typeof instance !== 'object' || instance == null) {
36 | throw new Error(
37 | 'Failed to create MMKV instance - an unknown object was returned by createMMKV(..)!'
38 | );
39 | }
40 | }
41 | return instance as NativeMMKV;
42 | };
43 |
--------------------------------------------------------------------------------
/package/src/createMMKV.web.ts:
--------------------------------------------------------------------------------
1 | /* global localStorage */
2 | import type { Configuration, NativeMMKV } from './Types';
3 | import { createTextEncoder } from './createTextEncoder';
4 |
5 | const canUseDOM =
6 | typeof window !== 'undefined' && window.document?.createElement != null;
7 |
8 | const hasAccessToLocalStorage = () => {
9 | try {
10 | // throws ACCESS_DENIED error
11 | window.localStorage;
12 |
13 | return true;
14 | } catch {
15 | return false;
16 | }
17 | };
18 |
19 | const KEY_WILDCARD = '\\';
20 | const inMemoryStorage = new Map();
21 |
22 | export const createMMKV = (config: Configuration): NativeMMKV => {
23 | if (config.encryptionKey != null) {
24 | throw new Error("MMKV: 'encryptionKey' is not supported on Web!");
25 | }
26 | if (config.path != null) {
27 | throw new Error("MMKV: 'path' is not supported on Web!");
28 | }
29 |
30 | // canUseDOM check prevents spam in Node server environments, such as Next.js server side props.
31 | if (!hasAccessToLocalStorage() && canUseDOM) {
32 | console.warn(
33 | 'MMKV: LocalStorage has been disabled. Your experience will be limited to in-memory storage!'
34 | );
35 | }
36 |
37 | const storage = () => {
38 | if (!canUseDOM) {
39 | throw new Error(
40 | 'Tried to access storage on the server. Did you forget to call this in useEffect?'
41 | );
42 | }
43 |
44 | if (!hasAccessToLocalStorage()) {
45 | return {
46 | getItem: (key: string) => inMemoryStorage.get(key) ?? null,
47 | setItem: (key: string, value: string) =>
48 | inMemoryStorage.set(key, value),
49 | removeItem: (key: string) => inMemoryStorage.delete(key),
50 | clear: () => inMemoryStorage.clear(),
51 | length: inMemoryStorage.size,
52 | key: (index: number) => Object.keys(inMemoryStorage).at(index) ?? null,
53 | } as Storage;
54 | }
55 |
56 | const domStorage =
57 | global?.localStorage ?? window?.localStorage ?? localStorage;
58 | if (domStorage == null) {
59 | throw new Error(`Could not find 'localStorage' instance!`);
60 | }
61 | return domStorage;
62 | };
63 |
64 | const textEncoder = createTextEncoder();
65 |
66 | if (config.id.includes(KEY_WILDCARD)) {
67 | throw new Error(
68 | 'MMKV: `id` cannot contain the backslash character (`\\`)!'
69 | );
70 | }
71 |
72 | const keyPrefix = `${config.id}${KEY_WILDCARD}`; // mmkv.default\\
73 | const prefixedKey = (key: string) => {
74 | if (key.includes('\\')) {
75 | throw new Error(
76 | 'MMKV: `key` cannot contain the backslash character (`\\`)!'
77 | );
78 | }
79 | return `${keyPrefix}${key}`;
80 | };
81 |
82 | return {
83 | clearAll: () => {
84 | const keys = Object.keys(storage());
85 | for (const key of keys) {
86 | if (key.startsWith(keyPrefix)) {
87 | storage().removeItem(key);
88 | }
89 | }
90 | },
91 | delete: (key) => storage().removeItem(prefixedKey(key)),
92 | set: (key, value) => {
93 | storage().setItem(prefixedKey(key), value.toString());
94 | },
95 | getString: (key) => storage().getItem(prefixedKey(key)) ?? undefined,
96 | getNumber: (key) => {
97 | const value = storage().getItem(prefixedKey(key));
98 | if (value == null) return undefined;
99 | return Number(value);
100 | },
101 | getBoolean: (key) => {
102 | const value = storage().getItem(prefixedKey(key));
103 | if (value == null) return undefined;
104 | return value === 'true';
105 | },
106 | getBuffer: (key) => {
107 | const value = storage().getItem(prefixedKey(key));
108 | if (value == null) return undefined;
109 | return textEncoder.encode(value).buffer;
110 | },
111 | getAllKeys: () => {
112 | const keys = Object.keys(storage());
113 | return keys
114 | .filter((key) => key.startsWith(keyPrefix))
115 | .map((key) => key.slice(keyPrefix.length));
116 | },
117 | contains: (key) => storage().getItem(prefixedKey(key)) != null,
118 | recrypt: () => {
119 | throw new Error('`recrypt(..)` is not supported on Web!');
120 | },
121 | size: 0,
122 | isReadOnly: false,
123 | trim: () => {
124 | // no-op
125 | },
126 | };
127 | };
128 |
--------------------------------------------------------------------------------
/package/src/createTextEncoder.ts:
--------------------------------------------------------------------------------
1 | /* global TextEncoder */
2 | export function createTextEncoder(): TextEncoder {
3 | if (global.TextEncoder != null) {
4 | return new global.TextEncoder();
5 | } else {
6 | return {
7 | encode: () => {
8 | throw new Error('TextEncoder is not supported in this environment!');
9 | },
10 | encodeInto: () => {
11 | throw new Error('TextEncoder is not supported in this environment!');
12 | },
13 | encoding: 'utf-8',
14 | };
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/package/src/hooks.ts:
--------------------------------------------------------------------------------
1 | import { useRef, useState, useMemo, useCallback, useEffect } from 'react';
2 | import { MMKV } from './MMKV';
3 | import type { Configuration } from './Types';
4 |
5 | function isConfigurationEqual(
6 | left?: Configuration,
7 | right?: Configuration
8 | ): boolean {
9 | if (left == null || right == null) return left == null && right == null;
10 |
11 | return (
12 | left.encryptionKey === right.encryptionKey &&
13 | left.id === right.id &&
14 | left.path === right.path &&
15 | left.mode === right.mode
16 | );
17 | }
18 |
19 | let defaultInstance: MMKV | null = null;
20 | function getDefaultInstance(): MMKV {
21 | if (defaultInstance == null) {
22 | defaultInstance = new MMKV();
23 | }
24 | return defaultInstance;
25 | }
26 |
27 | /**
28 | * Use the default, shared MMKV instance.
29 | */
30 | export function useMMKV(): MMKV;
31 | /**
32 | * Use a custom MMKV instance with the given configuration.
33 | * @param configuration The configuration to initialize the MMKV instance with. Does not have to be memoized.
34 | */
35 | export function useMMKV(configuration: Configuration): MMKV;
36 | export function useMMKV(configuration?: Configuration): MMKV {
37 | const instance = useRef();
38 | const lastConfiguration = useRef();
39 |
40 | if (configuration == null) return getDefaultInstance();
41 |
42 | if (
43 | instance.current == null ||
44 | !isConfigurationEqual(lastConfiguration.current, configuration)
45 | ) {
46 | lastConfiguration.current = configuration;
47 | instance.current = new MMKV(configuration);
48 | }
49 |
50 | return instance.current;
51 | }
52 |
53 | function createMMKVHook<
54 | T extends (boolean | number | string | ArrayBufferLike) | undefined,
55 | TSet extends T | undefined,
56 | TSetAction extends TSet | ((current: T) => TSet),
57 | >(getter: (instance: MMKV, key: string) => T) {
58 | return (
59 | key: string,
60 | instance?: MMKV
61 | ): [value: T, setValue: (value: TSetAction) => void] => {
62 | const mmkv = instance ?? getDefaultInstance();
63 |
64 | const [bump, setBump] = useState(0);
65 | const value = useMemo(() => {
66 | // bump is here as an additional outside dependency, so this useMemo
67 | // re-computes the value each time bump changes, effectively acting as a hint
68 | // that the outside value (storage) has changed. setting bump refreshes this value.
69 | bump;
70 | return getter(mmkv, key);
71 | }, [mmkv, key, bump]);
72 |
73 | // update value by user set
74 | const set = useCallback(
75 | (v: TSetAction) => {
76 | const newValue = typeof v === 'function' ? v(getter(mmkv, key)) : v;
77 | switch (typeof newValue) {
78 | case 'number':
79 | case 'string':
80 | case 'boolean':
81 | mmkv.set(key, newValue);
82 | break;
83 | case 'undefined':
84 | mmkv.delete(key);
85 | break;
86 | case 'object':
87 | if (newValue instanceof ArrayBuffer) {
88 | mmkv.set(key, newValue);
89 | break;
90 | } else {
91 | throw new Error(
92 | `MMKV: Type object (${newValue}) is not supported!`
93 | );
94 | }
95 | default:
96 | throw new Error(`MMKV: Type ${typeof newValue} is not supported!`);
97 | }
98 | },
99 | [key, mmkv]
100 | );
101 |
102 | // update value if it changes somewhere else (second hook, same key)
103 | useEffect(() => {
104 | const listener = mmkv.addOnValueChangedListener((changedKey) => {
105 | if (changedKey === key) {
106 | setBump((b) => b + 1);
107 | }
108 | });
109 | return () => listener.remove();
110 | }, [key, mmkv]);
111 |
112 | return [value, set];
113 | };
114 | }
115 |
116 | /**
117 | * Use the string value of the given `key` from the given MMKV storage instance.
118 | *
119 | * If no instance is provided, a shared default instance will be used.
120 | *
121 | * @example
122 | * ```ts
123 | * const [username, setUsername] = useMMKVString("user.name")
124 | * ```
125 | */
126 | export const useMMKVString = createMMKVHook((instance, key) =>
127 | instance.getString(key)
128 | );
129 |
130 | /**
131 | * Use the number value of the given `key` from the given MMKV storage instance.
132 | *
133 | * If no instance is provided, a shared default instance will be used.
134 | *
135 | * @example
136 | * ```ts
137 | * const [age, setAge] = useMMKVNumber("user.age")
138 | * ```
139 | */
140 | export const useMMKVNumber = createMMKVHook((instance, key) =>
141 | instance.getNumber(key)
142 | );
143 | /**
144 | * Use the boolean value of the given `key` from the given MMKV storage instance.
145 | *
146 | * If no instance is provided, a shared default instance will be used.
147 | *
148 | * @example
149 | * ```ts
150 | * const [isPremiumAccount, setIsPremiumAccount] = useMMKVBoolean("user.isPremium")
151 | * ```
152 | */
153 | export const useMMKVBoolean = createMMKVHook((instance, key) =>
154 | instance.getBoolean(key)
155 | );
156 | /**
157 | * Use the buffer value (unsigned 8-bit (0-255)) of the given `key` from the given MMKV storage instance.
158 | *
159 | * If no instance is provided, a shared default instance will be used.
160 | *
161 | * @example
162 | * ```ts
163 | * const [privateKey, setPrivateKey] = useMMKVBuffer("user.privateKey")
164 | * ```
165 | */
166 | export const useMMKVBuffer = createMMKVHook((instance, key) =>
167 | instance.getBuffer(key)
168 | );
169 | /**
170 | * Use an object value of the given `key` from the given MMKV storage instance.
171 | *
172 | * If no instance is provided, a shared default instance will be used.
173 | *
174 | * The object will be serialized using `JSON`.
175 | *
176 | * @example
177 | * ```ts
178 | * const [user, setUser] = useMMKVObject("user")
179 | * ```
180 | */
181 | export function useMMKVObject(
182 | key: string,
183 | instance?: MMKV
184 | ): [
185 | value: T | undefined,
186 | setValue: (
187 | value: T | undefined | ((prevValue: T | undefined) => T | undefined)
188 | ) => void,
189 | ] {
190 | const [json, setJson] = useMMKVString(key, instance);
191 |
192 | const value = useMemo(() => {
193 | if (json == null) return undefined;
194 | return JSON.parse(json) as T;
195 | }, [json]);
196 |
197 | const setValue = useCallback(
198 | (v: (T | undefined) | ((prev: T | undefined) => T | undefined)) => {
199 | if (v instanceof Function) {
200 | setJson((currentJson) => {
201 | const currentValue =
202 | currentJson != null ? (JSON.parse(currentJson) as T) : undefined;
203 | const newValue = v(currentValue);
204 | // Store the Object as a serialized Value or clear the value
205 | return newValue != null ? JSON.stringify(newValue) : undefined;
206 | });
207 | } else {
208 | // Store the Object as a serialized Value or clear the value
209 | const newValue = v != null ? JSON.stringify(v) : undefined;
210 | setJson(newValue);
211 | }
212 | },
213 | [setJson]
214 | );
215 |
216 | return [value, setValue];
217 | }
218 |
219 | /**
220 | * Listen for changes in the given MMKV storage instance.
221 | * If no instance is passed, the default instance will be used.
222 | * @param valueChangedListener The function to call whenever a value inside the storage instance changes
223 | * @param instance The instance to listen to changes to (or the default instance)
224 | *
225 | * @example
226 | * ```ts
227 | * useMMKVListener((key) => {
228 | * console.log(`Value for "${key}" changed!`)
229 | * })
230 | * ```
231 | */
232 | export function useMMKVListener(
233 | valueChangedListener: (key: string) => void,
234 | instance?: MMKV
235 | ): void {
236 | const ref = useRef(valueChangedListener);
237 | ref.current = valueChangedListener;
238 |
239 | const mmkv = instance ?? getDefaultInstance();
240 |
241 | useEffect(() => {
242 | const listener = mmkv.addOnValueChangedListener((changedKey) => {
243 | ref.current(changedKey);
244 | });
245 | return () => listener.remove();
246 | }, [mmkv]);
247 | }
248 |
--------------------------------------------------------------------------------
/package/src/index.ts:
--------------------------------------------------------------------------------
1 | export * from './MMKV';
2 | export * from './hooks';
3 |
4 | export { Mode, type Configuration } from './Types';
5 |
--------------------------------------------------------------------------------
/package/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "rootDir": ".",
4 | "paths": {
5 | "react-native-mmkv": [
6 | "./src/index"
7 | ]
8 | },
9 | "allowUnreachableCode": false,
10 | "allowUnusedLabels": false,
11 | "esModuleInterop": true,
12 | "forceConsistentCasingInFileNames": true,
13 | "jsx": "react",
14 | "lib": [
15 | "esnext",
16 | "DOM"
17 | ],
18 | "module": "esnext",
19 | "moduleResolution": "node",
20 | "noFallthroughCasesInSwitch": true,
21 | "noImplicitReturns": true,
22 | "noStrictGenericChecks": false,
23 | "noUnusedLocals": true,
24 | "noUnusedParameters": true,
25 | "noUncheckedIndexedAccess": true,
26 | "resolveJsonModule": true,
27 | "skipLibCheck": true,
28 | "strict": true,
29 | "target": "esnext",
30 | },
31 | "include": [
32 | "src",
33 | ".eslintrc.js",
34 | "babel.config.js",
35 | "react-native.config.js",
36 | ]
37 | }
38 |
--------------------------------------------------------------------------------
/tea.yaml:
--------------------------------------------------------------------------------
1 | # https://tea.xyz/what-is-this-file
2 | ---
3 | version: 1.0.0
4 | codeOwners:
5 | - '0xcF3c286e7cDED19D87f61E85B3370283C885bA88'
6 | quorum: 1
7 |
--------------------------------------------------------------------------------