Git Product home page Git Product logo

mrousavy / react-native-mmkv Goto Github PK

View Code? Open in Web Editor NEW
5.2K 30.0 229.0 10.49 MB

⚡️ The fastest key/value storage for React Native. ~30x faster than AsyncStorage!

License: Other

CMake 1.02% C++ 32.87% JavaScript 1.59% Java 5.49% TypeScript 29.26% Swift 0.06% C 0.10% Objective-C 3.29% Ruby 2.91% Objective-C++ 23.00% Shell 0.41%
mmkv react react-native jsi android ios turbomodule native-module cpp jni

react-native-mmkv's Introduction

VisionCamera

MMKV

The fastest key/value storage for React Native.


  • MMKV is an efficient, small mobile key-value storage framework developed by WeChat. See Tencent/MMKV for more information
  • react-native-mmkv is a library that allows you to easily use MMKV inside your React Native applications. It provides fast and direct bindings to the native C++ library which are accessible through a simple JS API.

Features

  • Get and set strings, booleans and numbers
  • Fully synchronous calls, no async/await, no Promises, no Bridge.
  • Encryption support (secure storage)
  • Multiple instances support (separate user-data with global data)
  • Customize storage location
  • High performance because everything is written in C++
  • ~30x faster than AsyncStorage
  • Uses JSI instead of the "old" Bridge
  • iOS, Android and Web support
  • Easy to use React Hooks API

Sponsors

react-native-mmkv is sponsored by getstream.io.
Try the React Native Chat tutorial 💬

Benchmark

StorageBenchmark compares popular storage libraries against each other by reading a value from storage for 1000 times:

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

Installation

React Native

yarn add react-native-mmkv
cd ios && pod install

Expo

npx expo install react-native-mmkv
npx expo prebuild

Usage

Create a new instance

To create a new instance of the MMKV storage, use the MMKV constructor. It is recommended that you re-use this instance throughout your entire app instead of creating a new instance each time, so export the storage object.

Default

import { MMKV } from 'react-native-mmkv'

export const storage = new MMKV()

This creates a new storage instance using the default MMKV storage ID (mmkv.default).

App Groups

If you want to share MMKV data between your app and other apps or app extensions in the same group, open Info.plist and create an AppGroup key with your app group's value. MMKV will then automatically store data inside the app group which can be read and written to from other apps or app extensions in the same group by making use of MMKV's multi processing mode. See Configuring App Groups.

Customize

import { MMKV } from 'react-native-mmkv'

export const storage = new MMKV({
  id: `user-${userId}-storage`,
  path: `${USER_DIRECTORY}/storage`,
  encryptionKey: 'hunter2'
})

This creates a new storage instance using a custom MMKV storage ID. By using a custom storage ID, your storage is separated from the default MMKV storage of your app.

The following values can be configured:

  • id: The MMKV instance's ID. If you want to use multiple instances, use different IDs. For example, you can separate the global app's storage and a logged-in user's storage. (required if path or encryptionKey fields are specified, otherwise defaults to: 'mmkv.default')
  • path: The MMKV instance's root path. By default, MMKV stores file inside $(Documents)/mmkv/. You can customize MMKV's root directory on MMKV initialization (documentation: iOS / Android)
  • 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 / Android)

Set

storage.set('user.name', 'Marc')
storage.set('user.age', 21)
storage.set('is-mmkv-fast-asf', true)

Get

const username = storage.getString('user.name') // 'Marc'
const age = storage.getNumber('user.age') // 21
const isMmkvFastAsf = storage.getBoolean('is-mmkv-fast-asf') // true

Keys

// checking if a specific key exists
const hasUsername = storage.contains('user.name')

// getting all keys
const keys = storage.getAllKeys() // ['user.name', 'user.age', 'is-mmkv-fast-asf']

// delete a specific key + value
storage.delete('user.name')

// delete all keys
storage.clearAll()

Objects

const user = {
  username: 'Marc',
  age: 21
}

// Serialize the object into a JSON string
storage.set('user', JSON.stringify(user))

// Deserialize the JSON string into an object
const jsonUser = storage.getString('user') // { 'username': 'Marc', 'age': 21 }
const userObject = JSON.parse(jsonUser)

Encryption

// encrypt all data with a private key
storage.recrypt('hunter2')

// remove encryption
storage.recrypt(undefined)

Buffers

storage.set('someToken', new Uint8Array([1, 100, 255]))
const buffer = storage.getBuffer('someToken')
console.log(buffer) // [1, 100, 255]

Testing with Jest

A mocked MMKV instance is automatically used when testing with Jest, so you will be able to use new MMKV() as per normal in your tests. Refer to example/test/MMKV.test.ts for an example.

Documentation

LocalStorage and In-Memory Storage (Web)

If a user chooses to disable LocalStorage in their browser, the library will automatically provide a limited in-memory storage as an alternative. However, this in-memory storage won't persist data, and users may experience data loss if they refresh the page or close their browser. To optimize user experience, consider implementing a suitable solution within your app to address this scenario.

Limitations

As the library uses JSI for synchronous native methods access, remote debugging (e.g. with Chrome) is no longer possible. Instead, you should use Flipper.

Flipper

Use flipper-plugin-react-native-mmkv to debug your MMKV storage using Flipper. You can also simply console.log an MMKV instance.

Reactotron

Use reactotron-react-native-mmkv to automatically log writes to your MMKV storage using Reactotron. See the docs for how to setup this plugin with Reactotron.

Community Discord

Join the Margelo Community Discord to chat about react-native-mmkv or other Margelo libraries.

Adopting at scale

react-native-mmkv is provided as is, I work on it in my free time.

If you're integrating react-native-mmkv in a production app, consider funding this project and contact me to receive premium enterprise support, help with issues, prioritize bugfixes, request features, help at integrating react-native-mmkv, and more.

Contributing

See the contributing guide to learn how to contribute to the repository and the development workflow.

License

MIT

react-native-mmkv's People

Contributors

alirezahadjar avatar andrewcorliss avatar androideveloper avatar dependabot[bot] avatar dimaportenko avatar eyousefifar avatar fahad86 avatar fobos531 avatar hwhh avatar janicduplessis avatar leleka14 avatar matheusmatos avatar mrousavy avatar mthahzan avatar myckhel avatar ngocle2497 avatar osdnk avatar riamon-v avatar richardlindhout avatar robinsoncol avatar ruibinch avatar samherbert avatar siderakis avatar sregg avatar swain avatar titozzz avatar todorone avatar umangloria avatar yangjonghun avatar yfunk avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-native-mmkv's Issues

Handling large amounts of data using redux-persist

Platform

  • Android

Issue Description

I'm trying to vet this storage engine as possible alternative to using AsyncStorage. But I can't seem to get android to behave correctly when I add a lot of data to state. In our android app at around 35-40Mb the app crashes.

It's closed source so I can't provide much in terms of code snippets but here's the logs, based on what I can tell MMKV falls on its face and stops persisting data after it can't allocate any more memory. I find that strange considering it's a small amount of data.

Is there some way to circumvent this from happening? Surely mmkv can scale better than this?

2021-04-07 17:27:23.019 9940-9940/com.movista.*** D/ApkSoSource: not allowing consideration of lib/x86/libmmkvnative.so: deferring to libdir
2021-04-07 17:27:26.916 9940-10024/com.movista.*** I/MMKV: <MMKV.cpp:156::initialize> version v1.2.7 page size:4096
2021-04-07 17:27:26.916 9940-10024/com.movista.*** I/MMKV: <MMKV.cpp:198::initializeMMKV> root dir: /data/user/0/com.movista.***/files/mmkv
2021-04-07 17:27:29.125 9940-10032/com.movista.*** I/MMKV: <MMKV_IO.cpp:81::loadFromFile> loading [mmkv.default] with 0 actual size, file size 4096, InterProcess 0, meta info version:0
2021-04-07 17:27:29.126 9940-10032/com.movista.*** I/MMKV: <MMKV_IO.cpp:130::loadFromFile> loaded [mmkv.default] with 0 key-values
2021-04-07 17:27:30.257 9940-10032/com.movista.*** I/MMKV: <MMKV_IO.cpp:367::ensureMemorySize> extending [mmkv.default] file size from 4096 to 16384, incoming size:989, future usage:7976
2021-04-07 17:28:33.686 9940-10032/com.movista.*** I/MMKV: <MMKV_IO.cpp:367::ensureMemorySize> extending [mmkv.default] file size from 16384 to 262144, incoming size:14211, future usage:132136
2021-04-07 17:28:41.561 9940-10032/com.movista.*** I/MMKV: <MMKV_IO.cpp:367::ensureMemorySize> extending [mmkv.default] file size from 262144 to 134217728, incoming size:11615236, future usage:93043816
2021-04-07 17:29:16.524 9940-10032/com.movista.*** I/MMKV: <MMKV_IO.cpp:367::ensureMemorySize> extending [mmkv.default] file size from 134217728 to 1073741824, incoming size:46415236, future usage:649843840
2021-04-07 17:29:20.822 9940-10032/com.movista.*** E/MMKV: <MemoryFile.cpp:117::mmap> fail to mmap [/data/user/0/com.movista.***/files/mmkv/mmkv.default], Out of memory

As a general question, is this library designed to handle large amounts of data? The upper limit I'm trying to reach currently is at about 300Mb.

Let me know if I need to provide any more info! Thanks! 😄

[ios] ld: symbol(s) not found for architecture x86_64

When I added this library to my project, I can't built it, due below error:

act-native-mmkv/react_native_mmkv.framework/react_native_mmkv
Undefined symbols for architecture x86_64:
  "facebook::jsi::Value::Value(facebook::jsi::Value&&)", referenced from:
      void std::__1::allocator<facebook::jsi::Value>::construct<facebook::jsi::Value, facebook::jsi::Value>(facebook::jsi::Value*, facebook::jsi::Value&&) in YeetJSIUtils.o
  "facebook::jsi::Object::getPropertyAsFunction(facebook::jsi::Runtime&, char const*) const", referenced from:
      createPromiseAsJSIValue(facebook::jsi::Runtime&, std::__1::function<void (facebook::jsi::Runtime&, std::__1::shared_ptr<Promise>)>) in YeetJSIUtils.o
  "facebook::jsi::Value::~Value()", referenced from:
      void facebook::jsi::Object::setProperty<facebook::jsi::Function>(facebook::jsi::Runtime&, facebook::jsi::String const&, facebook::jsi::Function&&) in Mmkv.o
      facebook::jsi::Value::Value(facebook::jsi::Runtime&, facebook::jsi::Object const&) in Mmkv.o
      facebook::jsi::Value::Value<facebook::jsi::String>(facebook::jsi::String&&) in Mmkv.o
      facebook::jsi::Value::Value<facebook::jsi::Array>(facebook::jsi::Array&&) in Mmkv.o
      convertNSDictionaryToJSIObject(facebook::jsi::Runtime&, NSDictionary*) in YeetJSIUtils.o
      convertNSArrayToJSIArray(facebook::jsi::Runtime&, NSArray*) in YeetJSIUtils.o
      convertNSArrayToStdVector(facebook::jsi::Runtime&, NSArray*) in YeetJSIUtils.o
      ...
  "facebook::jsi::Value::Value(facebook::jsi::Runtime&, facebook::jsi::Value const&)", referenced from:
      facebook::jsi::detail::toValue(facebook::jsi::Runtime&, facebook::jsi::Value const&) in YeetJSIUtils.o
  "facebook::jsi::JSError::JSError(facebook::jsi::Runtime&, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >)", referenced from:
      facebook::jsi::JSError::JSError(facebook::jsi::Runtime&, char const*) in Mmkv.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Below you can find a pod file

require_relative '../node_modules/react-native/scripts/react_native_pods'
require_relative '../node_modules/@react-native-community/cli-platform-ios/native_modules'

platform :ios, '11.0'
use_frameworks!

def shared_dependencies()
    # Other pods
    pod 'AppCenter', '1.13.1'
    pod 'PromiseKit', '~> 6.0'
end

target 'MyApp' do
    config = use_native_modules!
    use_react_native!(:path => config["reactNativePath"])
    shared_dependencies()

end

Maybe it is related to use_frameowork issue ?

Crash on Release android

Library works fine on debug but crashes on Release mode. Only happens on Android.
The library is simply installed no usages in the code.
Worked fine without Reanimated 2

03-15 17:16:32.799 10257 10338 I MMKV    : <MMKV.cpp:156::initialize> version v1.2.7 page size:4096
03-15 17:16:32.800 10257 10338 I MMKV    : <MMKV.cpp:167::initialize> armv8 AES instructions is supported
03-15 17:16:32.800 10257 10338 I MMKV    : <MMKV.cpp:175::initialize> armv8 CRC32 instructions is supported
03-15 17:16:32.800 10257 10338 I MMKV    : <MMKV.cpp:198::initializeMMKV> root dir: /data/user/0/com.app.cooe/files/mmkv
03-15 17:16:32.800 10257 10338 F libc    : Fatal signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 0x188f2 in tid 10338 (mqt_native_modu), pid 10257 (com.app.cooe)
03-15 17:16:32.842 10257 10337 I HermesVM: JSI rethrowing JS exception: Requiring unknown module "95".
03-15 17:16:32.842 10257 10337 I HermesVM: 
03-15 17:16:32.842 10257 10337 I HermesVM: Error: Requiring unknown module "95".
03-15 17:16:32.842 10257 10337 I HermesVM:     at v (address at index.android.bundle:1:119296)
03-15 17:16:32.842 10257 10337 I HermesVM:     at d (address at index.android.bundle:1:119038)
03-15 17:16:32.842 10257 10337 I HermesVM:     at o (address at index.android.bundle:1:118707)
03-15 17:16:32.842 10257 10337 I HermesVM:     at global (address at index.android.bundle:1:118428)
03-15 17:16:32.937 10346 10346 I crash_dump64: obtaining output fd from tombstoned, type: kDebuggerdTombstone
03-15 17:16:32.937  1258  1258 I /system/bin/tombstoned: received crash request for pid 10338
03-15 17:16:32.938 10346 10346 I crash_dump64: performing dump of process 10257 (target tid = 10338)
03-15 17:16:32.954 10346 10346 F DEBUG   : *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
03-15 17:16:32.954 10346 10346 F DEBUG   : Build fingerprint: 'OnePlus/OnePlus7T/OnePlus7T:10/QKQ1.190716.003/2005192100:user/release-keys'
03-15 17:16:32.954 10346 10346 F DEBUG   : Revision: '0'
03-15 17:16:32.954 10346 10346 F DEBUG   : ABI: 'arm64'
03-15 17:16:32.954 10346 10346 F DEBUG   : Timestamp: 2021-03-15 17:16:32+0400
03-15 17:16:32.955 10346 10346 F DEBUG   : pid: 10257, tid: 10338, name: mqt_native_modu  >>> com.app.cooe <<<
03-15 17:16:32.955 10346 10346 F DEBUG   : uid: 10549
03-15 17:16:32.955 10346 10346 F DEBUG   : signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 0x188f2
03-15 17:16:32.955 10346 10346 F DEBUG   :     x0  00000000000188f2  x1  ffff0070e146f610  x2  0000000000000046  x3  0000000600000008
03-15 17:16:32.955 10346 10346 F DEBUG   :     x4  0000000000000046  x5  0000000000000008  x6  0000000000000007  x7  00000070e2c42560
03-15 17:16:32.955 10346 10346 F DEBUG   :     x8  00000070e3d4be60  x9  00000000000188fa  x10 000000000046f610  x11 00000070ec684ad0
03-15 17:16:32.955 10346 10346 F DEBUG   :     x12 00000070e10274e8  x13 0000000000000001  x14 0000000000000007  x15 0000000000000000
03-15 17:16:32.955 10346 10346 F DEBUG   :     x16 00000071f26978f0  x17 00000071f2689860  x18 00000070e1d5c000  x19 00000070ec682000
03-15 17:16:32.955 10346 10346 F DEBUG   :     x20 00000070ec5174d8  x21 0000000600000008  x22 0000000000000046  x23 00000070e2c45020
03-15 17:16:32.955 10346 10346 F DEBUG   :     x24 00000070ec6842a0  x25 00000070ec5174d8  x26 00000070e10274e8  x27 0000000000000046
03-15 17:16:32.955 10346 10346 F DEBUG   :     x28 00000070e2c45020  x29 00000070e2c42450
03-15 17:16:32.955 10346 10346 F DEBUG   :     sp  00000070e2c423f0  lr  00000070e694ffc4  pc  00000070e69500ec

Cannot find source file: node_modules/react-native/ReactCommon/jsi/jsi/jsi.cpp

build failed in android
error in android studio:

CMake Error at ***/node_modules/react-native-mmkv/android/CMakeLists.txt:15 (add_library):
 Cannot find source file:

   ../node_modules/react-native/ReactCommon/jsi/jsi/jsi.cpp

 Tried extensions .c .C .c++ .cc .cpp .cxx .m .M .mm .h .hh .h++ .hm .hpp
 .hxx .in .txx

i do have /node_modules/react-native/ReactCommon/jsi/jsi/jsi.cpp exist

[v1.3.1]: Cannot create MMKV instance when passing value to either "path" or "encryptionKey"

The error "Error: Exception in HostFunction: " when passing either "path" or "encryptionKey" to the initialized object of MMKV class's constructor.

Reproducible example:
import { MMKV } from 'react-native-mmkv';

const storage = new MMKV({
id: 'some-id',
path: 'some-path',
encryptionKey: 'some-encryption-key',
});

I am using
react-native: 0.64.2
react-native-mmkv: 1.3.1

Safely migrate from AsyncStorage

Hello. I really want to replace in my app on all the place AsyncStorage and use MMKV. The problem I have is that I use async storage with redux persist and if I want to change to MMKV I will need to log out users as in redux persist I keep info if the user has a profile, authenticated, etc. Any idea maybe how safely do migration if it is possible?

FATAL EXCEPTION: create_react_context

app crash:

java.lang.UnsatisfiedLinkError: dalvik.system.PathClassLoader[DexPathList[[zip file "/data/app/com.fandengdushu.elearning-OgNUeAOCK1DzMhuUHXOymQ==/base.apk"],nativeLibraryDirectories=[/data/app/com.fandengdushu.elearning-OgNUeAOCK1DzMhuUHXOymQ==/lib/arm, /data/app/com.fandengdushu.elearning-OgNUeAOCK1DzMhuUHXOymQ==/base.apk!/lib/armeabi-v7a, /system/lib, /system/product/lib]]] couldn't find "libcpp.so"
Process: com.fandengdushu.elearning, PID: 32418
    java.lang.UnsatisfiedLinkError: dalvik.system.PathClassLoader[DexPathList[[zip file "/data/app/com.fandengdushu.elearning-eCUYOjb8H8IzYMhKFpsOkQ==/base.apk"],nativeLibraryDirectories=[/data/app/com.fandengdushu.elearning-eCUYOjb8H8IzYMhKFpsOkQ==/lib/arm, /data/app/com.fandengdushu.elearning-eCUYOjb8H8IzYMhKFpsOkQ==/base.apk!/lib/armeabi-v7a, /system/lib, /system/product/lib]]] couldn't find "libcpp.so"
        at java.lang.Runtime.loadLibrary0(Runtime.java:1067)
        at java.lang.Runtime.loadLibrary0(Runtime.java:1007)
        at java.lang.System.loadLibrary(System.java:1667)
        at com.reactnativemmkv.MmkvModule.<clinit>(MmkvModule.kt:17)
        at com.reactnativemmkv.MmkvPackage.createNativeModules(MmkvPackage.kt:11)
        at com.facebook.react.ReactPackageHelper.getNativeModuleIterator(ReactPackageHelper.java:42)
        at com.facebook.react.NativeModuleRegistryBuilder.processPackage(NativeModuleRegistryBuilder.java:42)
        at com.facebook.react.ReactInstanceManager.processPackage(ReactInstanceManager.java:1347)
        at com.facebook.react.ReactInstanceManager.processPackages(ReactInstanceManager.java:1318)
        at com.facebook.react.ReactInstanceManager.createReactContext(ReactInstanceManager.java:1240)
        at com.facebook.react.ReactInstanceManager.access$1100(ReactInstanceManager.java:131)
        at com.facebook.react.ReactInstanceManager$5.run(ReactInstanceManager.java:1023)
        at java.lang.Thread.run(Thread.java:919)

M.MMKC.delete is not a function - Android Release Mode

Our app is live in-store with this behavior, any help?

Current behavior

MMKV functions are undefined.

Expected behavior

Should work properly, functions should not be undefined.

Environment

  • Platforms tested:
    • Android
    • iOS
    • macOS
    • Windows
  • MMKV version: 1.0.6
  • Environment:

System:
OS: macOS 10.15.7
CPU: (12) x64 Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
Memory: 1.97 GB / 16.00 GB
Shell: 5.7.1 - /bin/zsh
Binaries:
Node: 14.15.1 - ~/.nvm/versions/node/v14.15.1/bin/node
Yarn: 1.22.10 - ~/pegacredito/PegaCredito/node_modules/.bin/yarn
npm: 6.14.8 - ~/.nvm/versions/node/v14.15.1/bin/npm
Watchman: 4.9.0 - /usr/local/bin/watchman
Managers:
CocoaPods: 1.10.0 - /usr/local/bin/pod
SDKs:
iOS SDK:
Platforms: iOS 14.4, DriverKit 20.2, macOS 11.1, tvOS 14.3, watchOS 7.2
Android SDK:
API Levels: 23, 28, 29, 30
Build Tools: 28.0.3, 29.0.2, 29.0.3, 30.0.0
System Images: android-18 | Google APIs Intel x86 Atom, android-19 | Google APIs Intel x86 Atom, android-26 | Google APIs Intel x86 Atom, android-27 | Intel x86 Atom_64, android-28 | Google APIs Intel x86 Atom_64, android-30 | Google APIs Intel x86 Atom, android-30 | Google Play Intel x86 Atom
Android NDK: 22.0.7026061
npmPackages:
@react-native-community/cli: Not Found
react: 16.13.1 => 16.13.1
react-native: 0.63.3 => 0.63.3

MMKV does not correctly autolink

MMKV does not show up in the left side of Android Studio (dependencies), and can therefore not be imported (as shown in the installation step in the readme).

The current workaround for this is:

  1. Add this to settings.gradle:
include ':react-native-mmkv'
project(':react-native-mmkv').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-mmkv/android/')
  1. Add this to build.gradle (in app/), inside of dependencies (under implementation("com.facebook.react:react-native:+")):
  implementation project(':react-native-mmkv')

I am not sure what is missing from my configuration, but this will likely change soon when TurboModules will be released (maybe RN 0.65?), because I will rewrite the library - no extra installation steps will be needed then!

Web

Could be cool to add web support, maybe with store or just localStorage directly.

Android - package com.reactnativemmkv does not exist

React 16.13.1
MMKV 1.2.0

After adding via yarn add react-native-mmkv I've run pod install and everything is working correctly on IOS.

I've followed the directions in the read me.

  • added ExampleJSIPackage.java with the provided code snippet.
  • In MainApplication.java i've added the provided method. (Android studio auto completes with the package name)

Screenshots

Screen Shot 2021-07-20 at 3 02 43 PM

Screen Shot 2021-07-20 at 2 59 12 PM

MMKV is undefined on iOS

It not always the case, in most cases our app startup normal.

But around 10% of which, the startup will crash directly because MMKV is undefined. and when it happens it require an app kill and restart to resume functioning.

We are using react-native 0.64

import { MMKV } from 'react-native-mmkv';
MMKV.getString(key)
"react-native-mmkv": "^1.1.6",

TypeError: _reactNativeMmkv.MMKV.set is not a function

Steps
yarn install
cd ios && pod install

import {MMKV} from 'react-native-mmkv
...
MMKV.set(email, LAST_TYPED_EMAIL)

After entering that code I get the error TypeError: _reactNativeMmkv.MMKV.set is not a function. Furthermore, after logging the MKV object, I have attached the following screen. It seems there is an issue with the native code and JS not being linked as all the methods are undefined.

Screen Shot 2021-02-24 at 9 16 57 PM

Missing source.properties file

Hi,
I tried installing you library as desribed here (https://github.com/mrousavy/react-native-mmkv/blob/master/INSTALL.md). I also have reanimated2 installed.
First a question: In the documentation for reanimated2 the installation guide states that the ReanimatedJSIModulePackage() has to be added in the Method getJSIModulePackage(). Your installation guide does not show that step in the code snippet from your installation guide (see bellow).

import com.facebook.react.bridge.JSIModulePackage;

public class MainApplication extends Application implements ReactApplication {

  private final ReactNativeHost mReactNativeHost =
      new ReactNativeHost(this) {
        @Override
        public boolean getUseDeveloperSupport() {
          return BuildConfig.DEBUG;
        }

        @Override
        protected List<ReactPackage> getPackages() {
          return new PackageList(this).getPackages();
        }

        @Override
        protected String getJSMainModuleName() {
          return "index";
        }

        // Add this method here!
        @Override
        protected JSIModulePackage getJSIModulePackage() {
          return new ExampleJSIPackage(); // Where is return new ReanimatedJSIModulePackage() ?
        }
      };

  // ...

If I follow your guide, i get the error :

A problem occurred configuring project ':react-native-mmkv'.
> com.android.builder.errors.EvalIssueException: NDK at C:\Users\alexa\AppData\Local\Android\Sdk\ndk\20.1.5948944 did not have a source.properties file

Have I done something wrong during the installation? Here a snippet from my MainApplication.java file

import com.facebook.react.bridge.JSIModulePackage; // <- add
import com.swmansion.reanimated.ReanimatedJSIModulePackage; // <- add

public class MainApplication extends MultiDexApplication implements ReactApplication {

  private final ReactNativeHost mReactNativeHost =
      new ReactNativeHost(this) {
        @Override
        public boolean getUseDeveloperSupport() {
          return BuildConfig.DEBUG;
        }

        @Override
        protected List<ReactPackage> getPackages() {
          @SuppressWarnings("UnnecessaryLocalVariable")
          List<ReactPackage> packages = new PackageList(this).getPackages();
          // Packages that cannot be autolinked yet can be added manually here, for example:
          // packages.add(new MyReactNativePackage());
          return packages;
        }

        @Override
        protected String getJSMainModuleName() {
          return "index";
        }

        /** 
        @Override
        protected JSIModulePackage getJSIModulePackage() {
          return new ReanimatedJSIModulePackage(); // <- For Reanimated2 Package
        }
       */

        @Override
        protected JSIModulePackage getJSIModulePackage() {
          return new ExampleJSIPackage(); // <-- For MMVK Package
        }
      };...

Thank you for your help! :)

[1.3.0] Crash on Android when start

I get this error when run android:
Fatal signal 6 (SIGABRT), code -6 in tid 6226 (create_react_co)
React Native: 0.64.2
mmkv: 1.3.0

enableHermes: true

App crash on android when activating Debug in RN

Hi, I'm having a consistent crash when I try to activate Debug from RN dev menu on the bundle pushed onto my device since I added this lib, here are the relevant logcat lines:

2021-03-09 17:29:07.708 29183-30012/? I/MMKV: <MMKV.cpp:198::initializeMMKV> root dir: /data/user/0/com.comwatt.myenergy/files/mmkv
2021-03-09 17:29:07.779 601-601/? E/cutils: Nothing there yet; let's create it: /storage/emulated/0/Android/data/com.comwatt.myenergy
2021-03-09 17:29:07.782 601-601/? E/cutils: Nothing there yet; let's create it: /storage/emulated/0/Android/data/com.comwatt.myenergy/cache
2021-03-09 17:29:08.920 30080-30080/? A/DEBUG: pid: 29183, tid: 30012, name: mqt_native_modu  >>> com.comwatt.myenergy <<<
2021-03-09 17:29:09.087 30080-30080/? A/DEBUG:       #00 pc 000000000002a080  /data/app/com.comwatt.myenergy-nYqAi17PbI44xu3gsfzsrw==/lib/arm64/libcpp.so (install(facebook::jsi::Runtime&)+56) (BuildId: 3e9507bd91d1bec3d4abb0e9d5608cdffb2a15aa)
2021-03-09 17:29:09.087 30080-30080/? A/DEBUG:       #01 pc 000000000002b070  /data/app/com.comwatt.myenergy-nYqAi17PbI44xu3gsfzsrw==/lib/arm64/libcpp.so (Java_com_reactnativemmkv_MmkvModule_nativeInstall+76) (BuildId: 3e9507bd91d1bec3d4abb0e9d5608cdffb2a15aa)
2021-03-09 17:29:09.087 30080-30080/? A/DEBUG:       #09 pc 0000000000000482  [anon:dalvik-classes32.dex extracted in memory from /data/app/com.comwatt.myenergy-nYqAi17PbI44xu3gsfzsrw==/base.apk!classes32.dex] (com.reactnativemmkv.MmkvModule.initialize+90)
2021-03-09 17:29:09.087 30080-30080/? A/DEBUG:       #12 pc 00000000002ddaae  [anon:dalvik-classes.dex extracted in memory from /data/app/com.comwatt.myenergy-nYqAi17PbI44xu3gsfzsrw==/base.apk] (com.facebook.react.bridge.ModuleHolder.doInitialize+90)
2021-03-09 17:29:09.087 30080-30080/? A/DEBUG:       #15 pc 00000000002ddb98  [anon:dalvik-classes.dex extracted in memory from /data/app/com.comwatt.myenergy-nYqAi17PbI44xu3gsfzsrw==/base.apk] (com.facebook.react.bridge.ModuleHolder.markInitializable+52)
2021-03-09 17:29:09.087 30080-30080/? A/DEBUG:       #18 pc 00000000002de19a  [anon:dalvik-classes.dex extracted in memory from /data/app/com.comwatt.myenergy-nYqAi17PbI44xu3gsfzsrw==/base.apk] (com.facebook.react.bridge.NativeModuleRegistry.notifyJSInstanceInitialized+82)
2021-03-09 17:29:09.087 30080-30080/? A/DEBUG:       #21 pc 00000000002d860c  [anon:dalvik-classes.dex extracted in memory from /data/app/com.comwatt.myenergy-nYqAi17PbI44xu3gsfzsrw==/base.apk] (com.facebook.react.bridge.CatalystInstanceImpl$4.run+12)
2021-03-09 17:29:09.087 30080-30080/? A/DEBUG:       #35 pc 00000000002e1a66  [anon:dalvik-classes.dex extracted in memory from /data/app/com.comwatt.myenergy-nYqAi17PbI44xu3gsfzsrw==/base.apk] (com.facebook.react.bridge.queue.MessageQueueThreadImpl$4.run+74)
2021-03-09 17:29:09.398 1471-30137/? W/ActivityTaskManager:   Force finishing activity com.comwatt.myenergy/.MainActivity
2021-03-09 17:29:09.399 1471-30138/? D/FrameworkEventCollector: recordAppIssue PN: com.comwatt.myenergy
2021-03-09 17:29:09.531 1471-2524/? W/InputDispatcher: channel '613a63b com.comwatt.myenergy/com.comwatt.myenergy.MainActivity (server)' ~ Consumer closed input channel or an error occurred.  events=0x9
2021-03-09 17:29:09.531 1471-2524/? E/InputDispatcher: channel '613a63b com.comwatt.myenergy/com.comwatt.myenergy.MainActivity (server)' ~ Channel is unrecoverably broken and will be disposed!
2021-03-09 17:29:09.534 1471-2521/? I/WindowManager: WIN DEATH: Window{613a63b u0 com.comwatt.myenergy/com.comwatt.myenergy.MainActivity}
2021-03-09 17:29:09.534 1471-2521/? W/InputDispatcher: Attempted to unregister already unregistered input channel '613a63b com.comwatt.myenergy/com.comwatt.myenergy.MainActivity (server)'
2021-03-09 17:29:09.534 1471-5677/? I/ActivityManager: Process com.comwatt.myenergy (pid 29183) has died: vis+99 TOP 
2021-03-09 17:29:09.553 1471-5677/? W/ActivityManager: Exception when unbinding service com.comwatt.myenergy/org.chromium.content.app.SandboxedProcessService1:0
    android.os.DeadObjectException
        at android.os.BinderProxy.transactNative(Native Method)
        at android.os.BinderProxy.transact(BinderProxy.java:557)
        at android.app.IApplicationThread$Stub$Proxy.scheduleUnbindService(IApplicationThread.java:1672)
        at com.android.server.am.ActiveServices.removeConnectionLocked(ActiveServices.java:3641)
        at com.android.server.am.ActiveServices.killServicesLocked(ActiveServices.java:4065)
        at com.android.server.am.ActivityManagerService.cleanUpApplicationRecordLocked(ActivityManagerService.java:14885)
        at com.android.server.am.ActivityManagerService.handleAppDiedLocked(ActivityManagerService.java:4028)
        at com.android.server.am.ActivityManagerService.appDiedLocked(ActivityManagerService.java:4223)
        at com.android.server.am.ActivityManagerService$AppDeathRecipient.binderDied(ActivityManagerService.java:1634)
        at android.os.BinderProxy.sendDeathNotice(BinderProxy.java:667)

Any idea where this might come from ? Weird emulated storage path ?

I can also confirm that removing the reference to MMKV fixes Debug mode.

Hooks

It would be great if the API would be more idiomatic with modern React and exposed some hooks.

In some of my projects I created a wrapper that looks like this:

  const { value, update, clear } = useAppSetting('someSetting');

value is the value, and it auto-updates in all consumers regardless of where it's being set from.
update and clear to update or clear the value

If you'd be up to this sort of implementation, I could come up with a PR for it.

Android crash on 1.2.5 (1.1.6 downgrade works)

Crash on startup on Android after upgrading to 1.2.5. Tried both with and without Hermes. Downgrade fixed it.

08-17 13:24:52.755 10097 10097 F DEBUG   : Build fingerprint: 'samsung/beyond1lteeea/beyond1:11/RP1A.200720.012/G973FXXSBFUF3:user/release-keys'
08-17 13:24:52.755 10097 10097 F DEBUG   : Revision: '26'
08-17 13:24:52.755 10097 10097 F DEBUG   : ABI: 'arm64'
08-17 13:24:52.755 10097 10097 F DEBUG   : Timestamp: 2021-08-17 13:24:52+0200
08-17 13:24:52.755 10097 10097 F DEBUG   : pid: 8714, tid: 10036, name: create_react_co  >>> com.themobilecompany.delijn <<<
08-17 13:24:52.755 10097 10097 F DEBUG   : uid: 10879
08-17 13:24:52.756 10097 10097 F DEBUG   : signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 0x2
08-17 13:24:52.756 10097 10097 F DEBUG   : Cause: null pointer dereference
08-17 13:24:52.756 10097 10097 F DEBUG   :     x0  000000000006800b  x1  000000709d4984d8  x2  00000072dee54508  x3  ffffffff9ee5c111
08-17 13:24:52.756 10097 10097 F DEBUG   :     x4  0027ab73c5000000  x5  000000705e543ae4  x6  000000743690f000  x7  0000000001f2e366
08-17 13:24:52.756 10097 10097 F DEBUG   :     x8  01012aa413b4937a  x9  01012aa413b4937a  x10 0000000000000000  x11 01012aa413b4937a
08-17 13:24:52.756 10097 10097 F DEBUG   :     x12 0000000000000018  x13 00000000611b9c84  x14 0028210ae675c86c  x15 000014be3f137182
08-17 13:24:52.756 10097 10097 F DEBUG   :     x16 000000705e7f9bb8  x17 000000742f50ff10  x18 0000007060c48000  x19 00000071aeee1560
08-17 13:24:52.756 10097 10097 F DEBUG   :     x20 000000709d498758  x21 0000000000000000  x22 000000709d4988b0  x23 000000716eebe6a0
08-17 13:24:52.756 10097 10097 F DEBUG   :     x24 000000716eebe6b0  x25 0000000000000002  x26 000000709d49a000  x27 0000000000000000
08-17 13:24:52.756 10097 10097 F DEBUG   :     x28 000000709d498980  x29 000000709d498710
08-17 13:24:52.756 10097 10097 F DEBUG   :     lr  000000705e543bac  sp  000000709d498580  pc  000000705e543bb0  pst 0000000060000000
08-17 13:24:52.830 10097 10097 F DEBUG   : backtrace:
08-17 13:24:52.830 10097 10097 F DEBUG   :       #00 pc 000000000002dbb0  /data/app/~~DS3Ycp2q_TS27axleI9rCA==/com.themobilecompany.delijn-z04o7lHYE5pYmfKr7xFvPQ==/lib/arm64/libhermes.so (facebook::hermes::HermesRuntimeImpl::call(facebook::jsi::Function const&, facebook::jsi::Value const&, facebook::jsi::Value const*, unsigned long)+204) (BuildId: 104108701ea35e3b32f33afab7ef38388a9e99aa)
08-17 13:24:52.830 10097 10097 F DEBUG   :       #01 pc 000000000002a2e8  /data/app/~~DS3Ycp2q_TS27axleI9rCA==/com.themobilecompany.delijn-z04o7lHYE5pYmfKr7xFvPQ==/lib/arm64/libmmkvnative.so (install(facebook::jsi::Runtime&)+144) (BuildId: 1e8957cd4588b8ceca49ec9166600921e517148a)
08-17 13:24:52.830 10097 10097 F DEBUG   :       #02 pc 000000000002b484  /data/app/~~DS3Ycp2q_TS27axleI9rCA==/com.themobilecompany.delijn-z04o7lHYE5pYmfKr7xFvPQ==/lib/arm64/libmmkvnative.so (Java_com_reactnativemmkv_MmkvModule_nativeInstall+80) (BuildId: 1e8957cd4588b8ceca49ec9166600921e517148a)
08-17 13:24:52.830 10097 10097 F DEBUG   :       #03 pc 000000000013eed4  /apex/com.android.art/lib64/libart.so (art_quick_generic_jni_trampoline+148) (BuildId: fe6bfaf552d16195430b86d57f169733)
08-17 13:24:52.830 10097 10097 F DEBUG   :       #04 pc 00000000001357e8  /apex/com.android.art/lib64/libart.so (art_quick_invoke_static_stub+568) (BuildId: fe6bfaf552d16195430b86d57f169733)
08-17 13:24:52.830 10097 10097 F DEBUG   :       #05 pc 00000000001ab804  /apex/com.android.art/lib64/libart.so (art::ArtMethod::Invoke(art::Thread*, unsigned int*, unsigned int, art::JValue*, char const*)+228) (BuildId: fe6bfaf552d16195430b86d57f169733)
08-17 13:24:52.831 10097 10097 F DEBUG   :       #06 pc 0000000000326090  /apex/com.android.art/lib64/libart.so (art::interpreter::ArtInterpreterToCompiledCodeBridge(art::Thread*, art::ArtMethod*, art::ShadowFrame*, unsigned short, art::JValue*)+376) (BuildId: fe6bfaf552d16195430b86d57f169733)
08-17 13:24:52.831 10097 10097 F DEBUG   :       #07 pc 000000000031c278  /apex/com.android.art/lib64/libart.so (bool art::interpreter::DoCall<false, false>(art::ArtMethod*, art::Thread*, art::ShadowFrame&, art::Instruction const*, unsigned short, art::JValue*)+912) (BuildId: fe6bfaf552d16195430b86d57f169733)
08-17 13:24:52.831 10097 10097 F DEBUG   :       #08 pc 000000000069490c  /apex/com.android.art/lib64/libart.so (MterpInvokeStatic+548) (BuildId: fe6bfaf552d16195430b86d57f169733)
08-17 13:24:52.831 10097 10097 F DEBUG   :       #09 pc 000000000012f994  /apex/com.android.art/lib64/libart.so (mterp_op_invoke_static+20) (BuildId: fe6bfaf552d16195430b86d57f169733)
08-17 13:24:52.831 10097 10097 F DEBUG   :       #10 pc 000000000009e20c  [anon:dalvik-classes2.dex extracted in memory from /data/app/~~DS3Ycp2q_TS27axleI9rCA==/com.themobilecompany.delijn-z04o7lHYE5pYmfKr7xFvPQ==/base.apk!classes2.dex] (com.reactnativemmkv.MmkvModule.install+8)
08-17 13:24:52.831 10097 10097 F DEBUG   :       #11 pc 0000000000694bb0  /apex/com.android.art/lib64/libart.so (MterpInvokeStatic+1224) (BuildId: fe6bfaf552d16195430b86d57f169733)
08-17 13:24:52.831 10097 10097 F DEBUG   :       #12 pc 000000000012f994  /apex/com.android.art/lib64/libart.so (mterp_op_invoke_static+20) (BuildId: fe6bfaf552d16195430b86d57f169733)
08-17 13:24:52.831 10097 10097 F DEBUG   :       #13 pc 0000000000000e6c  [anon:dalvik-classes4.dex extracted in memory from /data/app/~~DS3Ycp2q_TS27axleI9rCA==/com.themobilecompany.delijn-z04o7lHYE5pYmfKr7xFvPQ==/base.apk!classes4.dex] (com.themobilecompany.delijn.DeLijnJSIPackage.getJSIModules+56)
08-17 13:24:52.831 10097 10097 F DEBUG   :       #14 pc 0000000000693694  /apex/com.android.art/lib64/libart.so (MterpInvokeInterface+1812) (BuildId: fe6bfaf552d16195430b86d57f169733)
08-17 13:24:52.831 10097 10097 F DEBUG   :       #15 pc 000000000012fa14  /apex/com.android.art/lib64/libart.so (mterp_op_invoke_interface+20) (BuildId: fe6bfaf552d16195430b86d57f169733)
08-17 13:24:52.831 10097 10097 F DEBUG   :       #16 pc 00000000003d2564  [anon:dalvik-classes.dex extracted in memory from /data/app/~~DS3Ycp2q_TS27axleI9rCA==/com.themobilecompany.delijn-z04o7lHYE5pYmfKr7xFvPQ==/base.apk] (com.facebook.react.ReactInstanceManager.createReactContext+276)
08-17 13:24:52.831 10097 10097 F DEBUG   :       #17 pc 00000000006942d8  /apex/com.android.art/lib64/libart.so (MterpInvokeDirect+1248) (BuildId: fe6bfaf552d16195430b86d57f169733)
08-17 13:24:52.831 10097 10097 F DEBUG   :       #18 pc 000000000012f914  /apex/com.android.art/lib64/libart.so (mterp_op_invoke_direct+20) (BuildId: fe6bfaf552d16195430b86d57f169733)
08-17 13:24:52.831 10097 10097 F DEBUG   :       #19 pc 00000000003d2434  [anon:dalvik-classes.dex extracted in memory from /data/app/~~DS3Ycp2q_TS27axleI9rCA==/com.themobilecompany.delijn-z04o7lHYE5pYmfKr7xFvPQ==/base.apk] (com.facebook.react.ReactInstanceManager.access$1100)
08-17 13:24:52.831 10097 10097 F DEBUG   :       #20 pc 0000000000694bb0  /apex/com.android.art/lib64/libart.so (MterpInvokeStatic+1224) (BuildId: fe6bfaf552d16195430b86d57f169733)
08-17 13:24:52.831 10097 10097 F DEBUG   :       #21 pc 000000000012f994  /apex/com.android.art/lib64/libart.so (mterp_op_invoke_static+20) (BuildId: fe6bfaf552d16195430b86d57f169733)
08-17 13:24:52.831 10097 10097 F DEBUG   :       #22 pc 00000000003d1b54  [anon:dalvik-classes.dex extracted in memory from /data/app/~~DS3Ycp2q_TS27axleI9rCA==/com.themobilecompany.delijn-z04o7lHYE5pYmfKr7xFvPQ==/base.apk] (com.facebook.react.ReactInstanceManager$5.run+140)
08-17 13:24:52.831 10097 10097 F DEBUG   :       #23 pc 0000000000693694  /apex/com.android.art/lib64/libart.so (MterpInvokeInterface+1812) (BuildId: fe6bfaf552d16195430b86d57f169733)
08-17 13:24:52.831 10097 10097 F DEBUG   :       #24 pc 000000000012fa14  /apex/com.android.art/lib64/libart.so (mterp_op_invoke_interface+20) (BuildId: fe6bfaf552d16195430b86d57f169733)
08-17 13:24:52.831 10097 10097 F DEBUG   :       #25 pc 00000000000eb858  /apex/com.android.art/javalib/core-oj.jar (java.lang.Thread.run+8)
08-17 13:24:52.831 10097 10097 F DEBUG   :       #26 pc 0000000000313520  /apex/com.android.art/lib64/libart.so (art::interpreter::Execute(art::Thread*, art::CodeItemDataAccessor const&, art::ShadowFrame&, art::JValue, bool, bool) (.llvm.230246881315256824)+264) (BuildId: fe6bfaf552d16195430b86d57f169733)
08-17 13:24:52.831 10097 10097 F DEBUG   :       #27 pc 0000000000680138  /apex/com.android.art/lib64/libart.so (artQuickToInterpreterBridge+776) (BuildId: fe6bfaf552d16195430b86d57f169733)
08-17 13:24:52.831 10097 10097 F DEBUG   :       #28 pc 000000000013eff8  /apex/com.android.art/lib64/libart.so (art_quick_to_interpreter_bridge+88) (BuildId: fe6bfaf552d16195430b86d57f169733)
08-17 13:24:52.831 10097 10097 F DEBUG   :       #29 pc 0000000000135564  /apex/com.android.art/lib64/libart.so (art_quick_invoke_stub+548) (BuildId: fe6bfaf552d16195430b86d57f169733)
08-17 13:24:52.831 10097 10097 F DEBUG   :       #30 pc 00000000001ab7e8  /apex/com.android.art/lib64/libart.so (art::ArtMethod::Invoke(art::Thread*, unsigned int*, unsigned int, art::JValue*, char const*)+200) (BuildId: fe6bfaf552d16195430b86d57f169733)
08-17 13:24:52.831 10097 10097 F DEBUG   :       #31 pc 0000000000567e64  /apex/com.android.art/lib64/libart.so (art::JValue art::InvokeVirtualOrInterfaceWithJValues<art::ArtMethod*>(art::ScopedObjectAccessAlreadyRunnable const&, _jobject*, art::ArtMethod*, jvalue const*)+460) (BuildId: fe6bfaf552d16195430b86d57f169733)
08-17 13:24:52.831 10097 10097 F DEBUG   :       #32 pc 00000000005b8154  /apex/com.android.art/lib64/libart.so (art::Thread::CreateCallback(void*)+1308) (BuildId: fe6bfaf552d16195430b86d57f169733)
08-17 13:24:52.831 10097 10097 F DEBUG   :       #33 pc 00000000000b10e8  /apex/com.android.runtime/lib64/bionic/libc.so (__pthread_start(void*)+64) (BuildId: f85239005a40452d2a5d593676124555)
08-17 13:24:52.831 10097 10097 F DEBUG   :       #34 pc 0000000000050a58  /apex/com.android.runtime/lib64/bionic/libc.so (__start_thread+64) (BuildId: f85239005a40452d2a5d593676124555)```

Crashes on iOS after mmkv setBridge

Since introducing react-native-mmkv into the app we have noticed an increase in crashes:
image

We have also seen a number of users complaining the app would not open after first installation, and have seen a drop in some metrics without any other explanation, that were fixed when mmkv was removed.

react-native 0.64.2 and react-native-mmkv 1.2.5

Stack trace:

Thread 0 Crashed:
0   Paired                        	0x0000000103111918 before + 0 (HermesExecutorFactory.cpp:123)
1   Paired                        	0x0000000103111918 before + 0 (decorator.h:404)
2   Paired                        	0x0000000103111918 Around + 0 (decorator.h:725)
3   Paired                        	0x0000000103111918 facebook::jsi::WithRuntimeDecorator<facebook::react::(anonymous namespace)::ReentrancyCheck, facebook::jsi::Runtime, facebook::jsi::Runtime>::Around::Around(facebook::react::(anonymous namespace)::... + 124 (decorator.h:724)
4   Paired                        	0x00000001031118d8 before + 36 (HermesExecutorFactory.cpp:112)
5   Paired                        	0x00000001031118d8 before + 36 (decorator.h:404)
6   Paired                        	0x00000001031118d8 Around + 40 (decorator.h:725)
7   Paired                        	0x00000001031118d8 facebook::jsi::WithRuntimeDecorator<facebook::react::(anonymous namespace)::ReentrancyCheck, facebook::jsi::Runtime, facebook::jsi::Runtime>::Around::Around(facebook::react::(anonymous namespace)::... + 60 (decorator.h:724)
8   Paired                        	0x0000000103110328 facebook::jsi::WithRuntimeDecorator<facebook::react::(anonymous namespace)::ReentrancyCheck, facebook::jsi::Runtime, facebook::jsi::Runtime>::createFunctionFromHostFunction(facebook::jsi::PropNameI... + 72 (decorator.h:675)
9   Paired                        	0x00000001033945a0 createFromHostFunction + 44 (jsi-inl.h:222)
10  Paired                        	0x00000001033945a0 install + 508 (Mmkv.mm:63)
11  Paired                        	0x00000001033945a0 -[Mmkv setup] + 844 (Mmkv.mm:140)
12  Paired                        	0x00000001033950b8 -[Mmkv setBridge:] + 52 (Mmkv.mm:147)
13  Foundation                    	0x00000001aa03ed80 -[NSObject(NSKeyValueCoding) setValue:forKey:] + 328 (NSKeyValueCoding.m:438)
14  Paired                        	0x0000000103161e44 -[RCTModuleData setBridgeForInstance] + 160 (RCTModuleData.mm:222)
15  Paired                        	0x0000000103161c28 -[RCTModuleData setUpInstanceAndBridge:] + 196 (RCTModuleData.mm:187)
16  Paired                        	0x0000000103194d98 RCTUnsafeExecuteOnMainQueueSync + 44 (RCTUtils.m:271)
17  Paired                        	0x0000000103162850 -[RCTModuleData instance] + 252 (RCTModuleData.mm:348)
18  Paired                        	0x000000010314b3e0 __49-[RCTCxxBridge _prepareModulesWithDispatchGroup:]_block_invoke + 160 (RCTCxxBridge.mm:962)
19  libdispatch.dylib             	0x00000001a89a1a84 _dispatch_call_block_and_release + 32 (init.c:1466)
20  libdispatch.dylib             	0x00000001a89a381c _dispatch_client_callout + 20 (object.m:559)
21  libdispatch.dylib             	0x00000001a89b1ce0 _dispatch_main_queue_callback_4CF + 996 (inline_internal.h:2543)
22  CoreFoundation                	0x00000001a8d30340 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 16 (CFRunLoop.c:1790)
23  CoreFoundation                	0x00000001a8d2a218 __CFRunLoopRun + 2524 (CFRunLoop.c:3118)
24  CoreFoundation                	0x00000001a8d29308 CFRunLoopRunSpecific + 600 (CFRunLoop.c:3242)
25  GraphicsServices              	0x00000001c03ac734 GSEventRunModal + 164 (GSEvent.c:2259)
26  UIKitCore                     	0x00000001ab7a775c -[UIApplication _run] + 1072 (UIApplication.m:3269)
27  UIKitCore                     	0x00000001ab7acfcc UIApplicationMain + 168 (UIApplication.m:4740)
28  Paired                        	0x0000000102d7159c main + 88 (main.m:14)
29  libdyld.dylib                 	0x00000001a89e5cf8 start + 4

Support for objects?

Feature request:
I see references to things like convertObjCObjectToJSIValue and the reverse but mmkv.mm doesn't seem to be exposing this functionality.

Would it be possible to get native object/dict support so one could avoid using JSON.stringify() (and rely on the native counter-part)? Or have you found that it's more trouble than it's worth?

_reactNativeMmkv.MMKV.set is not a function.

I used this module in an expo app to save a username, but it gives error.
[Unhandled promise rejection: TypeError: _reactNativeMmkv.MMKV.set is not a function. (In '_reactNativeMmkv.MMKV.set("user.name", "Marc")', '_reactNativeMmkv.MMKV.set' is undefined)]

@mrousavy @myckhel

synchronous not delete all my keys

i have an example code :

let keys = MMKV.getAllKeys();
keys.forEach(item => { MMKV.delete(item) });

but it's not delete all keys? how to fix that?

Unable to build on Mac Catalyst

I'm unable to build on Mac Catalyst with the same errors noted here: #10

I created a minimal reproduction here: https://github.com/ryanlntn/MacOSCatalystMMKV

I've tried messing with deployment targets as per the solution there without effect. I've also toyed with different compiler settings but haven't found anything that does more than change the error message a little. I'm not sure what the requirements are for JSI but I am using react-native-reanimated 2 on catalyst without this issue. Oddly enough they set a lower deployment target too.

CocoaPods could not find compatible versions for pod "react-native-mmkv"

Hi, I'm trying to install pods after installing the library but I'm getting this error. (I'm on a MacBook Air m1)

Any help would be great.

Analyzing dependencies
[!] CocoaPods could not find compatible versions for pod "react-native-mmkv":
  In Podfile:
    react-native-mmkv (from `../node_modules/react-native-mmkv`)

Specs satisfying the `react-native-mmkv (from `../node_modules/react-native-mmkv`)` dependency were found, but they required a higher minimum deployment target.

Build issue on iOS

Using react-native 0.63.4

Any idea how to fix it? Perhaps it’s related to the fact my project does not use Flipper?

image
image

Android: error: cannot find symbol MmkvModule.install

I installed this module and successfully used it on iOS. I then preceded with following the steps for setting up android with reanimated installed copying the code from the example. It could not find the module so I had to add it manually by adding

include ':react-native-mmkv'
project(':react-native-mmkv').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-mmkv/android/')

to settings.gradle and in build.gradle adding

implementation project(':react-native-mmkv')

As described here: #37

Strangely enough, it had added the code implementation 'com.tencent:mmkv-static:1.0.10' there from before but with that code it simply cannot load the module.

However when I try to build the project in android studio it fails with:

/Users/jakob/coding/my-app/android/app/src/main/java/com/striveapp/StriveJSIPackage.java:17: error: cannot find symbol
        MmkvModule.install(jsContext, reactApplicationContext.getFilesDir().getAbsolutePath() + "/mmkv");
                  ^
  symbol:   method install(JavaScriptContextHolder,String)
  location: class MmkvModule

Am I missing something here? Perhaps the module gets loaded incorrectly and thus cannot run the function? Just a noob with android development here, please tell me if you need some other information.

Android crash with V1.2.0

Describe the bug

Crashing in Android with v1.2.0

It was working perfectly with version 1.1.6, then after updating with latest version app started to crash, if I revert back to 1.1.6 it works.

Android logs

07-10 10:43:36.955 23729 23851 D SoLoader: Loaded: libreact_nativemodule_core.so
07-10 10:43:36.957 23729 23851 D SoLoader: Loaded: libturbomodulejsijni.so
07-10 10:43:36.967 23729 23851 I MMKV    : <MMKV.cpp:156::initialize> version v1.2.10, page size 4096, arch armeabi-v7a/NEON
07-10 10:43:36.967 23729 23851 I MMKV    : <MMKV.cpp:198::initializeMMKV> root dir: /data/user/0/com.appname/files/mmkv
07-10 10:43:36.967 23729 23851 I HermesVM: HermesRuntimeImpl::call: Unable to call function: stack overflow
07-10 10:43:36.968 23729 23851 F libc    : /buildbot/src/googleplex-android/ndk-release-r20/external/libcxx/../../external/libcxxabi/src/abort_message.cpp:73: abort_message: assertion "terminating with uncaught exception of type facebook::jsi::JSINativeException: HermesRuntimeImpl::call: Unable to call function: stack overflow" failed
07-10 10:43:37.422 23867 23867 D AndroidRuntime: >>>>>> START com.android.internal.os.RuntimeInit uid 10303 <<<<<<
07-10 10:43:37.436 23867 23867 W /system/bin/app_process32: Could not reserve sentinel fault page

Platform Information:

"react": "17.0.2",
"react-native": "0.64.2",
"react-native-reanimated": "^2.2.0",
"react-native-mmkv": "^1.2.0",

android

React-native 0.65.1 React-native MMKV :1.3.1
Failed to build on Android
C/C++: /Users/wangqiang/ttvc/TTvc/node_modules/react-native-mmkv/android/CMakeLists.txt debug|armeabi-v7a : CMake Error: The following variables are used in this project, but they are set to NOTFOUND.
Please set them or make sure they are set and tested correctly in the CMake files:
REACT_NATIVE_JNI_LIB
linked by target "reactnativemmkv" in directory /Users/wangqiang/ttvc/TTvc/node_modules/react-native-mmkv/android

iOS Build Configuration Release Fails

I get these four fatal errors when building in Release mode but everything works great in Debug mode.

/ios/Pods/Headers/Public/React-jsi/jsi/jsi.h:933:43: Use of undeclared identifier 'kindOf'

/ios/Pods/Headers/Public/React-jsi/jsi/jsi.h:933:43: No matching function for call to 'kindOf'

/ios/Pods/Headers/Public/React-jsi/jsi/jsi.h:934:5: Static_assert failed due to requirement 'std::is_base_of<facebook::jsi::Symbol, signed char &>::value || std::is_base_of<facebook::jsi::String, signed char &>::value || std::is_base_of<facebook::jsi::Object, signed char &>::value' "Value cannot be implicitly move-constructed from this type"

/ios/Pods/Headers/Public/React-jsi/jsi/jsi.h:939:26: Cannot allocate reference type 'signed char &' with new

Encryption?

Hello! Thank you for this awesome work. Just wondering what the status of encryption is in this library? Is it already part of it or on the roadmap?

ios

Ios often crashes during use,

  • (void)close {
    SCOPED_LOCK(g_lock);
    MMKVInfo("closing %@", m_mmapID);

    [g_instanceDic removeObjectForKey:m_mmapKey];
    }

The error is here
prompt: com.facebook.react.JavaScript (35): EXC_BAD_ACCESS (code=1, address=0x5c881fc33c18)
@mrousavy help me

_reactNativeMmkv.getAllKeys() is not a function

Hello guys. I have

image
this error.

My Code

import { MMKV } from "react-native-mmkv";

const mmkvController = (key, defaultValue) => {
    const allKeys = MMKV.getAllKeys();
    const filtered = allKeys.filter((val) => val === key);
    if (filtered.length === 0) MMKV.set(key, defaultValue);
    return true
};

export default mmkvController

React Native Version: 0.63.3
React Native MMKV Version : 1.1.6
React Version: 16.13.1

Adding Async/Promise and Callback Wrappers

People cann still have an easier option of keeping the storage calls async and this would make migration from other libraries much easier:

e.g.

MMKV.setAsync("key", "value")
.then(function() {});

MMKV.getStringAsync("key")
.then(function(value) {});
// OR
let value = await MMKV.getStringAsync("key")

Windows support

Would be nice to have support for react-native-windows.

I've already started working on this at the support-windows branch, but hit a roadblock because I couldn't add the MMKV/Core/core.vcxproj to my solution since that's VS 2015 and apparently my VS 2019 can't read that:

No idea how to add that without touching the submodule, but if anyone has some ideas let me know!

_reactNativeMmkv.MMKV.set is not a function

Version used - "react-native-mmkv": "1.1.6"

Tried implementing in my project but throwing error, am I doing something wrong

      import AsyncStorage from '@react-native-community/async-storage';
      import { applyMiddleware, compose, createStore } from 'redux';
      import { persistReducer, persistStore } from 'redux-persist';
      import { MMKV } from 'react-native-mmkv';
      import { Storage } from 'redux-persist';
      
      import thunkMiddleware from 'redux-thunk';
      import { appReducer } from './reducer';
      
      const rootReducer = (state: any, action: any) => {
        if (action.type === 'AppState/ClearCacheRdxConst') {
          return appReducer(undefined, action);
        }
        return appReducer(state, action);
      };
      
      const enhancers = [
        applyMiddleware(
          thunkMiddleware,
          // createLogger({
          //   collapsed: true,
          //   predicate: () => __DEV__,
          // }),
        ),
      ];
      
      // @ts-ignore
      const composeEnhancers =
        (__DEV__ &&
          typeof window !== 'undefined' &&
          window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__) ||
        compose;
      
      const enhancer = composeEnhancers(...enhancers);
      
      // Unfortunately redux-persist expects Promises,
      // so we have to wrap our sync calls with Promise resolvers/rejecters
      export const storage: Storage = {
        setItem: (key: string, value: string): Promise<boolean> => {
          MMKV.set(key, value);
          return Promise.resolve(true);
        },
        getItem: (key: string): Promise<string> => {
          const value = MMKV.getString(key);
          return Promise.resolve(value);
        },
        removeItem: (key: string): Promise<void> => {
          MMKV.delete(key);
          return Promise.resolve();
        },
      };
      
      const persistConfig = {
        key: 'root',
        storage: storage,
      };
      
      const persistedReducer = persistReducer(persistConfig, rootReducer);
      export const store = createStore(persistedReducer, undefined);
      export const persistor = persistStore(store);

Error:

Screen Shot 2021-05-03 at 12 11 26 PM

However in the android it is not even able to build:

Screen Shot 2021-05-03 at 12 16 00 PM

[question] support array value

Hey,
Does this library support arrays of simple values like string, boolean, numbers etc ? I would like to store last searched results inside mmkv.

example

import { MMKV } from 'react-native-mmkv';

MMKV.set('app-mmkv-key', [1,2,3])

android start failure error code 0x2 (1.2.1)

  • device: POCO M3
  • react-native: 0.64.2
  • react-native-mmkv: 1.2.1

at startup - the bundle file is downloaded, but it still beats with an error as with version 1.2.0

photo_2021-07-29_16-05-44

while rolled back to version 1.1.6 - everything works there, but I would like to fix the problem anyway

TypeError: undefined is not a function?

when i use this package, i get the error:

Possible Unhandled Promise Rejection (id: 0):
TypeError: undefined is not a function
TypeError: undefined is not a function
at anonymous (http://10.0.2.2:8081/src\utils\http.bundle?platform=android&dev=true&minify=false&modulesOnly=true&runModule=false&shallow=true:22:48)
at tryCallOne (http://10.0.2.2:8081/index.bundle?platform=android&dev=true&minify=false:27056:16)
at anonymous (http://10.0.2.2:8081/index.bundle?platform=android&dev=true&minify=false:27157:27)
at apply (native)
at anonymous (http://10.0.2.2:8081/index.bundle?platform=android&dev=true&minify=false:30708:26)
at _callTimer (http://10.0.2.2:8081/index.bundle?platform=android&dev=true&minify=false:30596:17)
at _callImmediatesPass (http://10.0.2.2:8081/index.bundle?platform=android&dev=true&minify=false:30635:17)
at callImmediates (http://10.0.2.2:8081/index.bundle?platform=android&dev=true&minify=false:30852:33)
at __callImmediates (http://10.0.2.2:8081/index.bundle?platform=android&dev=true&minify=false:2736:35)
at anonymous (http://10.0.2.2:8081/index.bundle?platform=android&dev=true&minify=false:2522:34)
at __guard (http://10.0.2.2:8081/index.bundle?platform=android&dev=true&minify=false:2719:15)
at flushedQueue (http://10.0.2.2:8081/index.bundle?platform=android&dev=true&minify=false:2521:21)
at callFunctionReturnFlushedQueue (http://10.0.2.2:8081/index.bundle?platform=android&dev=true&minify=false:2500:33)

login.js

import {MMKV} from 'react-native-mmkv

const {code, message, data} = await login({phone, password})
setLoading(false)

    if (code === 1) {
       MMKV.set('token', data.access_token)

      ToastAndroid.showWithGravity(
        message,
        ToastAndroid.SHORT,
        ToastAndroid.CENTER
      )
      navigation.navigate('Home');
    } else {
      setErrortext(message)
      return
    }

AxiosRequest.js

service.interceptors.request.use(config => {
  const token = MMKV.getString('token') || null

  if (config.headers['Content-Type']) {
    return config.headers['Content-Type']
    // console.log(config.headers['Content-Type'])
  } else {
    config.headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
  }
  config.headers['Authorization'] = `Bearer ${token}`
  return config
}, error => {
  return Promise.reject(error)
})

i don't know where is error?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.