react-native-mmkv 2.0.1 → 2.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -33,6 +33,7 @@
33
33
  * **~30x faster than AsyncStorage**
34
34
  * Uses [**JSI**](https://github.com/react-native-community/discussions-and-proposals/issues/91) instead of the "old" Bridge
35
35
  * **iOS**, **Android** and **Web** support
36
+ * Easy to use **React Hooks** API
36
37
 
37
38
  ## Sponsors
38
39
 
@@ -82,7 +83,7 @@ To create a new instance of the MMKV storage, use the `MMKV` constructor. It is
82
83
  ```js
83
84
  import { MMKV } from 'react-native-mmkv'
84
85
 
85
- const storage = new MMKV()
86
+ export const storage = new MMKV()
86
87
  ```
87
88
 
88
89
  This creates a new storage instance using the default MMKV storage ID (`mmkv.default`).
@@ -92,10 +93,10 @@ This creates a new storage instance using the default MMKV storage ID (`mmkv.def
92
93
  ```js
93
94
  import { MMKV } from 'react-native-mmkv'
94
95
 
95
- const storage = new MMKV({
96
+ export const storage = new MMKV({
96
97
  id: `user-${userId}-storage`,
97
98
  path: `${USER_DIRECTORY}/storage`,
98
- encryptionKey: 'some-encryption-key'
99
+ encryptionKey: 'hunter2'
99
100
  })
100
101
  ```
101
102
 
@@ -155,6 +156,16 @@ const jsonUser = storage.getString('user') // { 'username': 'Marc', 'age': 21 }
155
156
  const userObject = JSON.parse(jsonUser)
156
157
  ```
157
158
 
159
+ ### Encryption
160
+
161
+ ```js
162
+ // encrypt all data with a private key
163
+ storage.recrypt('hunter2')
164
+
165
+ // remove encryption
166
+ storage.recrypt(undefined)
167
+ ```
168
+
158
169
  ## Documentation
159
170
 
160
171
  * [Hooks](./docs/HOOKS.md)
@@ -163,6 +174,7 @@ const userObject = JSON.parse(jsonUser)
163
174
  * [Using MMKV with redux-persist](./docs/WRAPPER_REDUX.md)
164
175
  * [Using MMKV with mobx-persist-storage](./docs/WRAPPER_MOBX.md)
165
176
  * [Using MMKV with mobx-persist](./docs/WRAPPER_MOBXPERSIST.md)
177
+ * [Using MMKV with zustand persist-middleware](./docs/WRAPPER_ZUSTAND_PERSIST_MIDDLEWARE.md)
166
178
  * [How is this library different from **react-native-mmkv-storage**?](https://github.com/mrousavy/react-native-mmkv/issues/100#issuecomment-886477361)
167
179
 
168
180
  ## Limitations
@@ -13,9 +13,10 @@ include_directories(
13
13
  )
14
14
 
15
15
  if(${REACT_NATIVE_VERSION} LESS 66)
16
- set (
17
- INCLUDE_JSI_CPP
16
+ file(
17
+ TO_CMAKE_PATH
18
18
  "${NODE_MODULES_DIR}/react-native/ReactCommon/jsi/jsi/jsi.cpp"
19
+ INCLUDE_JSI_CPP
19
20
  )
20
21
  endif()
21
22
 
@@ -16,7 +16,18 @@ MmkvHostObject::MmkvHostObject(const std::string& instanceId, std::string path,
16
16
  std::string* pathPtr = path.size() > 0 ? &path : nullptr;
17
17
  std::string* cryptKeyPtr = cryptKey.size() > 0 ? &cryptKey : nullptr;
18
18
  instance = MMKV::mmkvWithID(instanceId, mmkv::DEFAULT_MMAP_SIZE, MMKV_SINGLE_PROCESS, cryptKeyPtr, pathPtr);
19
+
19
20
  if (instance == nullptr) {
21
+ // Check if instanceId is invalid
22
+ if (instanceId.empty()) {
23
+ throw std::runtime_error("Failed to create MMKV instance! `id` cannot be empty!");
24
+ }
25
+
26
+ // Check if encryptionKey is invalid
27
+ if (cryptKey.size() > 16) {
28
+ throw std::runtime_error("Failed to create MMKV instance! `encryptionKey` cannot be longer than 16 bytes!");
29
+ }
30
+
20
31
  throw std::runtime_error("Failed to create MMKV instance!");
21
32
  }
22
33
  }
@@ -31,6 +42,7 @@ std::vector<jsi::PropNameID> MmkvHostObject::getPropertyNames(jsi::Runtime& rt)
31
42
  result.push_back(jsi::PropNameID::forUtf8(rt, std::string("delete")));
32
43
  result.push_back(jsi::PropNameID::forUtf8(rt, std::string("getAllKeys")));
33
44
  result.push_back(jsi::PropNameID::forUtf8(rt, std::string("deleteAll")));
45
+ result.push_back(jsi::PropNameID::forUtf8(rt, std::string("recrypt")));
34
46
  return result;
35
47
  }
36
48
 
@@ -181,9 +193,33 @@ jsi::Value MmkvHostObject::get(jsi::Runtime& runtime, const jsi::PropNameID& pro
181
193
  const jsi::Value* arguments,
182
194
  size_t count) -> jsi::Value {
183
195
  instance->clearAll();
196
+
184
197
  return jsi::Value::undefined();
185
198
  });
186
199
  }
187
200
 
201
+ if (propName == "recrypt") {
202
+ // MMKV.recrypt(key)
203
+ return jsi::Function::createFromHostFunction(runtime,
204
+ jsi::PropNameID::forAscii(runtime, funcName),
205
+ 0,
206
+ [this](jsi::Runtime& runtime,
207
+ const jsi::Value& thisValue,
208
+ const jsi::Value* arguments,
209
+ size_t count) -> jsi::Value {
210
+ if (arguments[0].isUndefined()) {
211
+ // reset encryption key to "no encryption"
212
+ instance->reKey(nullptr);
213
+ } else if (arguments[0].isString()) {
214
+ // reKey(..) with new encryption-key
215
+ auto encryptionKey = arguments[0].getString(runtime).utf8(runtime);
216
+ instance->reKey(encryptionKey);
217
+ } else {
218
+ throw jsi::JSError(runtime, "First argument ('encryptionKey') has to be of type string (or undefined)!");
219
+ }
220
+ return jsi::Value::undefined();
221
+ });
222
+ }
223
+
188
224
  return jsi::Value::undefined();
189
225
  }
@@ -13,7 +13,25 @@
13
13
  MmkvHostObject::MmkvHostObject(NSString* instanceId, NSString* path, NSString* cryptKey) {
14
14
  NSData* cryptData = cryptKey == nil ? nil : [cryptKey dataUsingEncoding:NSUTF8StringEncoding];
15
15
  instance = [MMKV mmkvWithID:instanceId cryptKey:cryptData rootPath:path];
16
+
16
17
  if (instance == nil) {
18
+ // Check if instanceId is invalid
19
+ if ([instanceId length] == 0) {
20
+ throw std::runtime_error("Failed to create MMKV instance! `id` cannot be empty!");
21
+ }
22
+
23
+ // Check if encryptionKey is invalid
24
+ if (cryptData != nil && [cryptData length] > 16) {
25
+ throw std::runtime_error("Failed to create MMKV instance! `encryptionKey` cannot be longer than 16 bytes!");
26
+ }
27
+
28
+ // Check if path is invalid
29
+ NSFileManager* fileManager = [[NSFileManager alloc] init];
30
+ bool pathExists = [fileManager fileExistsAtPath:path isDirectory:nil];
31
+ if (!pathExists) {
32
+ throw std::runtime_error("Failed to create MMKV instance! The given Storage Path does not exist!");
33
+ }
34
+
17
35
  throw std::runtime_error("Failed to create MMKV instance!");
18
36
  }
19
37
  }
@@ -28,6 +46,7 @@ std::vector<jsi::PropNameID> MmkvHostObject::getPropertyNames(jsi::Runtime& rt)
28
46
  result.push_back(jsi::PropNameID::forUtf8(rt, std::string("delete")));
29
47
  result.push_back(jsi::PropNameID::forUtf8(rt, std::string("getAllKeys")));
30
48
  result.push_back(jsi::PropNameID::forUtf8(rt, std::string("deleteAll")));
49
+ result.push_back(jsi::PropNameID::forUtf8(rt, std::string("recrypt")));
31
50
  return result;
32
51
  }
33
52
 
@@ -73,7 +92,7 @@ jsi::Value MmkvHostObject::get(jsi::Runtime& runtime, const jsi::PropNameID& pro
73
92
  if (!arguments[0].isString()) throw jsi::JSError(runtime, "First argument ('key') has to be of type string!");
74
93
 
75
94
  auto keyName = convertJSIStringToNSString(runtime, arguments[0].getString(runtime));
76
- auto value = [instance getBoolForKey:keyName];
95
+ bool value = [instance getBoolForKey:keyName];
77
96
  return jsi::Value(value);
78
97
  });
79
98
  }
@@ -114,7 +133,7 @@ jsi::Value MmkvHostObject::get(jsi::Runtime& runtime, const jsi::PropNameID& pro
114
133
  return jsi::Value(value);
115
134
  });
116
135
  }
117
-
136
+
118
137
  if (propName == "contains") {
119
138
  // MMKV.contains(key: string)
120
139
  return jsi::Function::createFromHostFunction(runtime,
@@ -125,13 +144,13 @@ jsi::Value MmkvHostObject::get(jsi::Runtime& runtime, const jsi::PropNameID& pro
125
144
  const jsi::Value* arguments,
126
145
  size_t count) -> jsi::Value {
127
146
  if (!arguments[0].isString()) throw jsi::JSError(runtime, "First argument ('key') has to be of type string!");
128
-
147
+
129
148
  auto keyName = convertJSIStringToNSString(runtime, arguments[0].getString(runtime));
130
149
  bool containsKey = [instance containsKey:keyName];
131
150
  return jsi::Value(containsKey);
132
151
  });
133
152
  }
134
-
153
+
135
154
  if (propName == "delete") {
136
155
  // MMKV.delete(key: string)
137
156
  return jsi::Function::createFromHostFunction(runtime,
@@ -142,7 +161,7 @@ jsi::Value MmkvHostObject::get(jsi::Runtime& runtime, const jsi::PropNameID& pro
142
161
  const jsi::Value* arguments,
143
162
  size_t count) -> jsi::Value {
144
163
  if (!arguments[0].isString()) throw jsi::JSError(runtime, "First argument ('key') has to be of type string!");
145
-
164
+
146
165
  auto keyName = convertJSIStringToNSString(runtime, arguments[0].getString(runtime));
147
166
  [instance removeValueForKey:keyName];
148
167
  return jsi::Value::undefined();
@@ -177,5 +196,29 @@ jsi::Value MmkvHostObject::get(jsi::Runtime& runtime, const jsi::PropNameID& pro
177
196
  });
178
197
  }
179
198
 
199
+ if (propName == "recrypt") {
200
+ // MMKV.recrypt(key)
201
+ return jsi::Function::createFromHostFunction(runtime,
202
+ jsi::PropNameID::forAscii(runtime, funcName),
203
+ 0,
204
+ [this](jsi::Runtime& runtime,
205
+ const jsi::Value& thisValue,
206
+ const jsi::Value* arguments,
207
+ size_t count) -> jsi::Value {
208
+ if (arguments[0].isUndefined()) {
209
+ // reset encryption key to "no encryption"
210
+ [instance reKey:nil];
211
+ } else if (arguments[0].isString()) {
212
+ // reKey(..) with new encryption-key
213
+ NSString* encryptionKey = convertJSIStringToNSString(runtime, arguments[0].getString(runtime));
214
+ NSData* encryptionKeyBytes = [encryptionKey dataUsingEncoding:NSUTF8StringEncoding];
215
+ [instance reKey:encryptionKeyBytes];
216
+ } else {
217
+ throw jsi::JSError(runtime, "First argument ('encryptionKey') has to be of type string (or undefined)!");
218
+ }
219
+ return jsi::Value::undefined();
220
+ });
221
+ }
222
+
180
223
  return jsi::Value::undefined();
181
224
  }
package/ios/MmkvModule.h CHANGED
@@ -2,6 +2,4 @@
2
2
 
3
3
  @interface MmkvModule : NSObject <RCTBridgeModule>
4
4
 
5
- @property (nonatomic, assign) BOOL setBridgeOnMainQueue;
6
-
7
5
  @end
package/ios/MmkvModule.mm CHANGED
@@ -11,8 +11,6 @@
11
11
  using namespace facebook;
12
12
 
13
13
  @implementation MmkvModule
14
- @synthesize bridge = _bridge;
15
- @synthesize methodQueue = _methodQueue;
16
14
 
17
15
  RCT_EXPORT_MODULE(MMKV)
18
16
 
@@ -30,39 +28,41 @@ RCT_EXPORT_BLOCKING_SYNCHRONOUS_METHOD(install:(nullable NSString*)storageDirect
30
28
  if (cxxBridge == nil) {
31
29
  return @false;
32
30
  }
33
-
31
+
34
32
  using namespace facebook;
35
-
33
+
36
34
  auto jsiRuntime = (jsi::Runtime*) cxxBridge.runtime;
37
35
  if (jsiRuntime == nil) {
38
36
  return @false;
39
37
  }
40
38
  auto& runtime = *jsiRuntime;
41
-
42
- [MMKV initializeMMKV:storageDirectory];
43
-
39
+
40
+ RCTUnsafeExecuteOnMainQueueSync(^{
41
+ [MMKV initializeMMKV:storageDirectory];
42
+ });
43
+
44
44
  // MMKV.createNewInstance()
45
45
  auto mmkvCreateNewInstance = jsi::Function::createFromHostFunction(runtime,
46
- jsi::PropNameID::forAscii(runtime, "mmkvCreateNewInstance"),
47
- 1,
48
- [](jsi::Runtime& runtime,
49
- const jsi::Value& thisValue,
50
- const jsi::Value* arguments,
51
- size_t count) -> jsi::Value {
46
+ jsi::PropNameID::forAscii(runtime, "mmkvCreateNewInstance"),
47
+ 1,
48
+ [](jsi::Runtime& runtime,
49
+ const jsi::Value& thisValue,
50
+ const jsi::Value* arguments,
51
+ size_t count) -> jsi::Value {
52
52
  if (count != 1) {
53
53
  throw jsi::JSError(runtime, "MMKV.createNewInstance(..) expects one argument (object)!");
54
54
  }
55
55
  jsi::Object config = arguments[0].asObject(runtime);
56
-
56
+
57
57
  NSString* instanceId = [MmkvModule getPropertyAsStringOrNilFromObject:config propertyName:"id" runtime:runtime];
58
58
  NSString* path = [MmkvModule getPropertyAsStringOrNilFromObject:config propertyName:"path" runtime:runtime];
59
59
  NSString* encryptionKey = [MmkvModule getPropertyAsStringOrNilFromObject:config propertyName:"encryptionKey" runtime:runtime];
60
-
60
+
61
61
  auto instance = std::make_shared<MmkvHostObject>(instanceId, path, encryptionKey);
62
62
  return jsi::Object::createFromHostObject(runtime, instance);
63
63
  });
64
64
  runtime.global().setProperty(runtime, "mmkvCreateNewInstance", std::move(mmkvCreateNewInstance));
65
-
65
+
66
66
  NSLog(@"Installed global.mmkvCreateNewInstance!");
67
67
  return @true;
68
68
  }
@@ -19,7 +19,7 @@ const onValueChangedListeners = new Map();
19
19
  class MMKV {
20
20
  /**
21
21
  * Creates a new MMKV instance with the given Configuration.
22
- * If no custom `id` is supplied, `'default'` will be used.
22
+ * If no custom `id` is supplied, `'mmkv.default'` will be used.
23
23
  */
24
24
  constructor(configuration = {
25
25
  id: 'mmkv.default'
@@ -108,6 +108,21 @@ class MMKV {
108
108
  return func();
109
109
  }
110
110
 
111
+ recrypt(key) {
112
+ const func = this.getFunctionFromCache('recrypt');
113
+ return func(key);
114
+ }
115
+
116
+ toString() {
117
+ return `MMKV (${this.id}): [${this.getAllKeys().join(', ')}]`;
118
+ }
119
+
120
+ toJSON() {
121
+ return {
122
+ [this.id]: this.getAllKeys()
123
+ };
124
+ }
125
+
111
126
  addOnValueChangedListener(onValueChanged) {
112
127
  this.onValueChangedListeners.push(onValueChanged);
113
128
  return {
@@ -1 +1 @@
1
- {"version":3,"sources":["MMKV.ts"],"names":["onValueChangedListeners","Map","MMKV","constructor","configuration","id","nativeInstance","functionCache","has","set","get","getFunctionFromCache","functionName","onValuesAboutToChange","keys","length","setImmediate","key","listener","value","func","getBoolean","getString","getNumber","contains","delete","getAllKeys","clearAll","addOnValueChangedListener","onValueChanged","push","remove","index","indexOf","splice"],"mappings":";;;;;;;AAAA;;AACA;;;;AA0GA,MAAMA,uBAAuB,GAAG,IAAIC,GAAJ,EAAhC;AAEA;AACA;AACA;;AACO,MAAMC,IAAN,CAAoC;AAKzC;AACF;AACA;A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C;AAEA,WAAO;AACLE,MAAAA,MAAM,EAAE,MAAM;AACZ,cAAMC,KAAK,GAAG,KAAKhC,uBAAL,CAA6BiC,OAA7B,CAAqCJ,cAArC,CAAd;;AACA,YAAIG,KAAK,KAAK,CAAC,CAAf,EAAkB;AAChB,eAAKhC,uBAAL,CAA6BkC,MAA7B,CAAoCF,KAApC,EAA2C,CAA3C;AACD;AACF;AANI,KAAP;AAQD;;AAhGwC","sourcesContent":["import { unstable_batchedUpdates } from 'react-native';\nimport { createMMKV } from './createMMKV';\n\ninterface Listener {\n remove: () => void;\n}\n\n/**\n * Used for configuration of a single MMKV instance.\n */\nexport interface MMKVConfiguration {\n /**\n * The MMKV instance's ID. If you want to use multiple instances, make sure to use different IDs!\n *\n * @example\n * ```ts\n * const userStorage = new MMKV({ id: `user-${userId}-storage` })\n * const globalStorage = new MMKV({ id: 'global-app-storage' })\n * ```\n *\n * @default 'mmkv.default'\n */\n id: string;\n /**\n * The MMKV instance's root path. By default, MMKV stores file inside `$(Documents)/mmkv/`. You can customize MMKV's root directory on MMKV initialization:\n *\n * @example\n * ```ts\n * const temporaryStorage = new MMKV({ path: '/tmp/' })\n * ```\n */\n path?: string;\n /**\n * 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.\n *\n * @example\n * ```ts\n * const secureStorage = new MMKV({ encryptionKey: 'my-encryption-key!' })\n * ```\n */\n encryptionKey?: string;\n}\n\n/**\n * Represents a single MMKV instance.\n */\ninterface MMKVInterface {\n /**\n * Set a value for the given `key`.\n */\n set: (key: string, value: boolean | string | number) => void;\n /**\n * Get a boolean value for the given `key`.\n *\n * @default false\n */\n getBoolean: (key: string) => boolean;\n /**\n * Get a string value for the given `key`.\n *\n * @default undefined\n */\n getString: (key: string) => string | undefined;\n /**\n * Get a number value for the given `key`.\n *\n * @default 0\n */\n getNumber: (key: string) => number;\n /**\n * Checks whether the given `key` is being stored in this MMKV instance.\n */\n contains: (key: string) => boolean;\n /**\n * Delete the given `key`.\n */\n delete: (key: string) => void;\n /**\n * Get all keys.\n *\n * @default []\n */\n getAllKeys: () => string[];\n /**\n * Delete all keys.\n */\n clearAll: () => void;\n /**\n * Adds a value changed listener.\n */\n addOnValueChangedListener: (\n onValueChanged: (key: string) => void\n ) => Listener;\n}\n\nexport type NativeMMKV = Pick<\n MMKVInterface,\n | 'clearAll'\n | 'contains'\n | 'delete'\n | 'getAllKeys'\n | 'getBoolean'\n | 'getNumber'\n | 'getString'\n | 'set'\n>;\n\nconst onValueChangedListeners = new Map<string, ((key: string) => void)[]>();\n\n/**\n * A single MMKV instance.\n */\nexport class MMKV implements MMKVInterface {\n private nativeInstance: NativeMMKV;\n private functionCache: Partial<NativeMMKV>;\n private id: string;\n\n /**\n * Creates a new MMKV instance with the given Configuration.\n * If no custom `id` is supplied, `'default'` will be used.\n */\n constructor(configuration: MMKVConfiguration = { id: 'mmkv.default' }) {\n this.id = configuration.id;\n this.nativeInstance = createMMKV(configuration);\n this.functionCache = {};\n }\n\n private get onValueChangedListeners() {\n if (!onValueChangedListeners.has(this.id)) {\n onValueChangedListeners.set(this.id, []);\n }\n return onValueChangedListeners.get(this.id)!;\n }\n\n private getFunctionFromCache<T extends keyof NativeMMKV>(\n functionName: T\n ): NativeMMKV[T] {\n if (this.functionCache[functionName] == null) {\n this.functionCache[functionName] = this.nativeInstance[functionName];\n }\n return this.functionCache[functionName] as NativeMMKV[T];\n }\n\n private onValuesAboutToChange(keys: string[]) {\n if (this.onValueChangedListeners.length === 0) return;\n\n setImmediate(() => {\n unstable_batchedUpdates(() => {\n for (const key of keys) {\n for (const listener of this.onValueChangedListeners) {\n listener(key);\n }\n }\n });\n });\n }\n\n set(key: string, value: boolean | string | number): void {\n this.onValuesAboutToChange([key]);\n\n const func = this.getFunctionFromCache('set');\n return func(key, value);\n }\n getBoolean(key: string): boolean {\n const func = this.getFunctionFromCache('getBoolean');\n return func(key);\n }\n getString(key: string): string | undefined {\n const func = this.getFunctionFromCache('getString');\n return func(key);\n }\n getNumber(key: string): number {\n const func = this.getFunctionFromCache('getNumber');\n return func(key);\n }\n contains(key: string): boolean {\n const func = this.getFunctionFromCache('contains');\n return func(key);\n }\n delete(key: string): void {\n this.onValuesAboutToChange([key]);\n\n const func = this.getFunctionFromCache('delete');\n return func(key);\n }\n getAllKeys(): string[] {\n const func = this.getFunctionFromCache('getAllKeys');\n return func();\n }\n clearAll(): void {\n const keys = this.getAllKeys();\n this.onValuesAboutToChange(keys);\n\n const func = this.getFunctionFromCache('clearAll');\n return func();\n }\n\n addOnValueChangedListener(onValueChanged: (key: string) => void): Listener {\n this.onValueChangedListeners.push(onValueChanged);\n\n return {\n remove: () => {\n const index = this.onValueChangedListeners.indexOf(onValueChanged);\n if (index !== -1) {\n this.onValueChangedListeners.splice(index, 1);\n }\n },\n };\n }\n}\n"]}
1
+ {"version":3,"sources":["MMKV.ts"],"names":["onValueChangedListeners","Map","MMKV","constructor","configuration","id","nativeInstance","functionCache","has","set","get","getFunctionFromCache","functionName","onValuesAboutToChange","keys","length","setImmediate","key","listener","value","func","getBoolean","getString","getNumber","contains","delete","getAllKeys","clearAll","recrypt","toString","join","toJSON","addOnValueChangedListener","onValueChanged","push","remove","index","indexOf","splice"],"mappings":";;;;;;;AAAA;;AACA;;;;AAwHA,MAAMA,uBAAuB,GAAG,IAAIC,GAAJ,EAAhC;AAEA;AACA;AACA;;AACO,MAAMC,IAAN,CAAoC;AAKzC;AACF;AACA;AACA;AACEC,EAAAA,WAAW,CAACC,aAAgC,GAAG;AAAEC,IAAAA,EAAE,EAAE;AAAN,GAApC,EAA4D;AAAA;;AAAA;;AAAA;;AACrE,SAAKA,EAAL,GAAUD,aAAa,CAACC,EAAxB;AACA,SAAKC,cAAL,GAAsB,4BAAWF,aAAX,CAAtB;AACA,SAAKG,aAAL,GAAqB,EAArB;AACD;;AAEkC,MAAvBP,uBAAuB,GAAG;AACpC,QAAI,CAACA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,EAAAA,yBAAyB,CAACC,cAAD,EAAkD;AACzE,SAAKjC,uBAAL,CAA6BkC,IAA7B,CAAkCD,cAAlC;AAEA,WAAO;AACLE,MAAAA,MAAM,EAAE,MAAM;AACZ,cAAMC,KAAK,GAAG,KAAKpC,uBAAL,CAA6BqC,OAA7B,CAAqCJ,cAArC,CAAd;;AACA,YAAIG,KAAK,KAAK,CAAC,CAAf,EAAkB;AAChB,eAAKpC,uBAAL,CAA6BsC,MAA7B,CAAoCF,KAApC,EAA2C,CAA3C;AACD;AACF;AANI,KAAP;AAQD;;AA7GwC","sourcesContent":["import { unstable_batchedUpdates } from 'react-native';\nimport { createMMKV } from './createMMKV';\n\ninterface Listener {\n remove: () => void;\n}\n\n/**\n * Used for configuration of a single MMKV instance.\n */\nexport interface MMKVConfiguration {\n /**\n * The MMKV instance's ID. If you want to use multiple instances, make sure to use different IDs!\n *\n * @example\n * ```ts\n * const userStorage = new MMKV({ id: `user-${userId}-storage` })\n * const globalStorage = new MMKV({ id: 'global-app-storage' })\n * ```\n *\n * @default 'mmkv.default'\n */\n id: string;\n /**\n * The MMKV instance's root path. By default, MMKV stores file inside `$(Documents)/mmkv/`. You can customize MMKV's root directory on MMKV initialization:\n *\n * @example\n * ```ts\n * const temporaryStorage = new MMKV({ path: '/tmp/' })\n * ```\n */\n path?: string;\n /**\n * 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.\n *\n * Encryption keys can have a maximum length of 16 bytes.\n *\n * @example\n * ```ts\n * const secureStorage = new MMKV({ encryptionKey: 'my-encryption-key!' })\n * ```\n */\n encryptionKey?: string;\n}\n\n/**\n * Represents a single MMKV instance.\n */\ninterface MMKVInterface {\n /**\n * Set a value for the given `key`.\n */\n set: (key: string, value: boolean | string | number) => void;\n /**\n * Get a boolean value for the given `key`.\n *\n * @default false\n */\n getBoolean: (key: string) => boolean;\n /**\n * Get a string value for the given `key`.\n *\n * @default undefined\n */\n getString: (key: string) => string | undefined;\n /**\n * Get a number value for the given `key`.\n *\n * @default 0\n */\n getNumber: (key: string) => number;\n /**\n * Checks whether the given `key` is being stored in this MMKV instance.\n */\n contains: (key: string) => boolean;\n /**\n * Delete the given `key`.\n */\n delete: (key: string) => void;\n /**\n * Get all keys.\n *\n * @default []\n */\n getAllKeys: () => string[];\n /**\n * Delete all keys.\n */\n clearAll: () => void;\n /**\n * Sets (or updates) the encryption-key to encrypt all data in this MMKV instance with.\n *\n * To remove encryption, pass `undefined` as a key.\n *\n * Encryption keys can have a maximum length of 16 bytes.\n */\n recrypt: (key: string | undefined) => void;\n /**\n * Adds a value changed listener. The Listener will be called whenever any value\n * in this storage instance changes (set or delete).\n *\n * To unsubscribe from value changes, call `remove()` on the Listener.\n */\n addOnValueChangedListener: (\n onValueChanged: (key: string) => void\n ) => Listener;\n}\n\nexport type NativeMMKV = Pick<\n MMKVInterface,\n | 'clearAll'\n | 'contains'\n | 'delete'\n | 'getAllKeys'\n | 'getBoolean'\n | 'getNumber'\n | 'getString'\n | 'set'\n | 'recrypt'\n>;\n\nconst onValueChangedListeners = new Map<string, ((key: string) => void)[]>();\n\n/**\n * A single MMKV instance.\n */\nexport class MMKV implements MMKVInterface {\n private nativeInstance: NativeMMKV;\n private functionCache: Partial<NativeMMKV>;\n private id: string;\n\n /**\n * Creates a new MMKV instance with the given Configuration.\n * If no custom `id` is supplied, `'mmkv.default'` will be used.\n */\n constructor(configuration: MMKVConfiguration = { id: 'mmkv.default' }) {\n this.id = configuration.id;\n this.nativeInstance = createMMKV(configuration);\n this.functionCache = {};\n }\n\n private get onValueChangedListeners() {\n if (!onValueChangedListeners.has(this.id)) {\n onValueChangedListeners.set(this.id, []);\n }\n return onValueChangedListeners.get(this.id)!;\n }\n\n private getFunctionFromCache<T extends keyof NativeMMKV>(\n functionName: T\n ): NativeMMKV[T] {\n if (this.functionCache[functionName] == null) {\n this.functionCache[functionName] = this.nativeInstance[functionName];\n }\n return this.functionCache[functionName] as NativeMMKV[T];\n }\n\n private onValuesAboutToChange(keys: string[]) {\n if (this.onValueChangedListeners.length === 0) return;\n\n setImmediate(() => {\n unstable_batchedUpdates(() => {\n for (const key of keys) {\n for (const listener of this.onValueChangedListeners) {\n listener(key);\n }\n }\n });\n });\n }\n\n set(key: string, value: boolean | string | number): void {\n this.onValuesAboutToChange([key]);\n\n const func = this.getFunctionFromCache('set');\n return func(key, value);\n }\n getBoolean(key: string): boolean {\n const func = this.getFunctionFromCache('getBoolean');\n return func(key);\n }\n getString(key: string): string | undefined {\n const func = this.getFunctionFromCache('getString');\n return func(key);\n }\n getNumber(key: string): number {\n const func = this.getFunctionFromCache('getNumber');\n return func(key);\n }\n contains(key: string): boolean {\n const func = this.getFunctionFromCache('contains');\n return func(key);\n }\n delete(key: string): void {\n this.onValuesAboutToChange([key]);\n\n const func = this.getFunctionFromCache('delete');\n return func(key);\n }\n getAllKeys(): string[] {\n const func = this.getFunctionFromCache('getAllKeys');\n return func();\n }\n clearAll(): void {\n const keys = this.getAllKeys();\n this.onValuesAboutToChange(keys);\n\n const func = this.getFunctionFromCache('clearAll');\n return func();\n }\n recrypt(key: string | undefined): void {\n const func = this.getFunctionFromCache('recrypt');\n return func(key);\n }\n\n toString(): string {\n return `MMKV (${this.id}): [${this.getAllKeys().join(', ')}]`;\n }\n toJSON(): object {\n return {\n [this.id]: this.getAllKeys(),\n };\n }\n\n addOnValueChangedListener(onValueChanged: (key: string) => void): Listener {\n this.onValueChangedListeners.push(onValueChanged);\n\n return {\n remove: () => {\n const index = this.onValueChangedListeners.indexOf(onValueChanged);\n if (index !== -1) {\n this.onValueChangedListeners.splice(index, 1);\n }\n },\n };\n }\n}\n"]}
@@ -59,7 +59,10 @@ const createMMKV = config => {
59
59
  return Boolean((_storage$getItem3 = storage().getItem(key)) !== null && _storage$getItem3 !== void 0 ? _storage$getItem3 : false);
60
60
  },
61
61
  getAllKeys: () => Object.keys(storage()),
62
- contains: key => storage().getItem(key) != null
62
+ contains: key => storage().getItem(key) != null,
63
+ recrypt: () => {
64
+ throw new Error('`recrypt(..)` is not supported on Web!');
65
+ }
63
66
  };
64
67
  };
65
68
 
@@ -1 +1 @@
1
- {"version":3,"sources":["createMMKV.web.ts"],"names":["canUseDOM","window","document","createElement","createMMKV","config","id","Error","encryptionKey","path","storage","domStorage","global","localStorage","clearAll","clear","delete","key","removeItem","set","value","setItem","toString","getString","getItem","undefined","getNumber","Number","getBoolean","Boolean","getAllKeys","Object","keys","contains"],"mappings":";;;;;;;;;AAAA;AAGA,MAAMA,SAAS,GACb,OAAOC,MAAP,KAAkB,WAAlB,IAAiC,qBAAAA,MAAM,CAACC,QAAP,sEAAiBC,aAAjB,KAAkC,IADrE;;AAGO,MAAMC,UAAU,GAAIC,MAAD,IAA2C;AACnE,MAAIA,MAAM,CAACC,EAAP,KAAc,cAAlB,EAAkC;AAChC,UAAM,IAAIC,KAAJ,CAAU,qCAAV,CAAN;AACD;;AACD,MAAIF,MAAM,CAACG,aAAP,IAAwB,IAA5B,EAAkC;AAChC,UAAM,IAAID,KAAJ,CAAU,gDAAV,CAAN;AACD;;AACD,MAAIF,MAAM,CAACI,IAAP,IAAe,IAAnB,EAAyB;AACvB,UAAM,IAAIF,KAAJ,CAAU,uCAAV,CAAN;AACD;;AAED,QAAMG,OAAO,GAAG,MAAM;AAAA;;AACpB,QAAI,CAACV,SAAL,EAAgB;AACd,YAAM,IAAIO,KAAJ,CACJ,kFADI,CAAN;AAGD;;AACD,UAAMI,UAAU,8CACdC,MADc,4CACd,QAAQC,YADM,kFACUZ,MADV,4CACU,QAAQY,YADlB,uCACkCA,YADlD;;AAEA,QAAIF,UAAU,IAAI,IAAlB,EAAwB;AACtB,YAAM,IAAIJ,KAAJ,CAAW,yCAAX,CAAN;AACD;;AACD,WAAOI,UAAP;AACD,GAZD;;AAcA,SAAO;AACLG,IAAAA,QAAQ,EAAE,MAAMJ,OAAO,GAAGK,KAAV,EADX;AAELC,IAAAA,MAAM,EAAGC,GAAD,IAASP,OAAO,GAAGQ,UAAV,CAAqBD,GAArB,CAFZ;AAGLE,IAAAA,GAAG,EAAE,CAACF,GAAD,EAAMG,KAAN,KAAgBV,OAAO,GAAGW,OAAV,CAAkBJ,GAAlB,EAAuBG,KAAK,CAACE,QAAN,EAAvB,CAHhB;AAILC,IAAAA,SAAS,EAAGN,GAAD;AAAA;;AAAA,iCAASP,OAAO,GAAGc,OAAV,CAAkBP,GAAlB,CAAT,+DAAmCQ,SAAnC;AAAA,KAJN;AAKLC,IAAAA,SAAS,EAAGT,GAAD;AAAA;;AAAA,aAASU,MAAM,sBAACjB,OAAO,GAAGc,OAAV,CAAkBP,GAAlB,CAAD,iEAA2B,CAA3B,CAAf;AAAA,KALN;AAMLW,IAAAA,UAAU,EAAGX,GAAD;AAAA;;AAAA,aAASY,OAAO,sBAACnB,OAAO,GAAGc,OAAV,CAAkBP,GAAlB,CAAD,iEAA2B,KAA3B,CAAhB;AAAA,KANP;AAOLa,IAAAA,UAAU,EAAE,MAAMC,MAAM,CAACC,IAAP,CAAYtB,OAAO,EAAnB,CAPb;AAQLuB,IAAAA,QAAQ,EAAGhB,GAAD,IAASP,OAAO,GAAGc,OAAV,CAAkBP,GAAlB,KAA0B;AARxC,GAAP;AAUD,CAnCM","sourcesContent":["/* global localStorage */\nimport type { MMKVConfiguration, NativeMMKV } from 'react-native-mmkv';\n\nconst canUseDOM =\n typeof window !== 'undefined' && window.document?.createElement != null;\n\nexport const createMMKV = (config: MMKVConfiguration): NativeMMKV => {\n if (config.id !== 'mmkv.default') {\n throw new Error(\"MMKV: 'id' is not supported on Web!\");\n }\n if (config.encryptionKey != null) {\n throw new Error(\"MMKV: 'encryptionKey' is not supported on Web!\");\n }\n if (config.path != null) {\n throw new Error(\"MMKV: 'path' is not supported on Web!\");\n }\n\n const storage = () => {\n if (!canUseDOM) {\n throw new Error(\n 'Tried to access storage on the server. Did you forget to call this in useEffect?'\n );\n }\n const domStorage =\n global?.localStorage ?? window?.localStorage ?? localStorage;\n if (domStorage == null) {\n throw new Error(`Could not find 'localStorage' instance!`);\n }\n return domStorage;\n };\n\n return {\n clearAll: () => storage().clear(),\n delete: (key) => storage().removeItem(key),\n set: (key, value) => storage().setItem(key, value.toString()),\n getString: (key) => storage().getItem(key) ?? undefined,\n getNumber: (key) => Number(storage().getItem(key) ?? 0),\n getBoolean: (key) => Boolean(storage().getItem(key) ?? false),\n getAllKeys: () => Object.keys(storage()),\n contains: (key) => storage().getItem(key) != null,\n };\n};\n"]}
1
+ {"version":3,"sources":["createMMKV.web.ts"],"names":["canUseDOM","window","document","createElement","createMMKV","config","id","Error","encryptionKey","path","storage","domStorage","global","localStorage","clearAll","clear","delete","key","removeItem","set","value","setItem","toString","getString","getItem","undefined","getNumber","Number","getBoolean","Boolean","getAllKeys","Object","keys","contains","recrypt"],"mappings":";;;;;;;;;AAAA;AAGA,MAAMA,SAAS,GACb,OAAOC,MAAP,KAAkB,WAAlB,IAAiC,qBAAAA,MAAM,CAACC,QAAP,sEAAiBC,aAAjB,KAAkC,IADrE;;AAGO,MAAMC,UAAU,GAAIC,MAAD,IAA2C;AACnE,MAAIA,MAAM,CAACC,EAAP,KAAc,cAAlB,EAAkC;AAChC,UAAM,IAAIC,KAAJ,CAAU,qCAAV,CAAN;AACD;;AACD,MAAIF,MAAM,CAACG,aAAP,IAAwB,IAA5B,EAAkC;AAChC,UAAM,IAAID,KAAJ,CAAU,gDAAV,CAAN;AACD;;AACD,MAAIF,MAAM,CAACI,IAAP,IAAe,IAAnB,EAAyB;AACvB,UAAM,IAAIF,KAAJ,CAAU,uCAAV,CAAN;AACD;;AAED,QAAMG,OAAO,GAAG,MAAM;AAAA;;AACpB,QAAI,CAACV,SAAL,EAAgB;AACd,YAAM,IAAIO,KAAJ,CACJ,kFADI,CAAN;AAGD;;AACD,UAAMI,UAAU,8CACdC,MADc,4CACd,QAAQC,YADM,kFACUZ,MADV,4CACU,QAAQY,YADlB,uCACkCA,YADlD;;AAEA,QAAIF,UAAU,IAAI,IAAlB,EAAwB;AACtB,YAAM,IAAIJ,KAAJ,CAAW,yCAAX,CAAN;AACD;;AACD,WAAOI,UAAP;AACD,GAZD;;AAcA,SAAO;AACLG,IAAAA,QAAQ,EAAE,MAAMJ,OAAO,GAAGK,KAAV,EADX;AAELC,IAAAA,MAAM,EAAGC,GAAD,IAASP,OAAO,GAAGQ,UAAV,CAAqBD,GAArB,CAFZ;AAGLE,IAAAA,GAAG,EAAE,CAACF,GAAD,EAAMG,KAAN,KAAgBV,OAAO,GAAGW,OAAV,CAAkBJ,GAAlB,EAAuBG,KAAK,CAACE,QAAN,EAAvB,CAHhB;AAILC,IAAAA,SAAS,EAAGN,GAAD;AAAA;;AAAA,iCAASP,OAAO,GAAGc,OAAV,CAAkBP,GAAlB,CAAT,+DAAmCQ,SAAnC;AAAA,KAJN;AAKLC,IAAAA,SAAS,EAAGT,GAAD;AAAA;;AAAA,aAASU,MAAM,sBAACjB,OAAO,GAAGc,OAAV,CAAkBP,GAAlB,CAAD,iEAA2B,CAA3B,CAAf;AAAA,KALN;AAMLW,IAAAA,UAAU,EAAGX,GAAD;AAAA;;AAAA,aAASY,OAAO,sBAACnB,OAAO,GAAGc,OAAV,CAAkBP,GAAlB,CAAD,iEAA2B,KAA3B,CAAhB;AAAA,KANP;AAOLa,IAAAA,UAAU,EAAE,MAAMC,MAAM,CAACC,IAAP,CAAYtB,OAAO,EAAnB,CAPb;AAQLuB,IAAAA,QAAQ,EAAGhB,GAAD,IAASP,OAAO,GAAGc,OAAV,CAAkBP,GAAlB,KAA0B,IARxC;AASLiB,IAAAA,OAAO,EAAE,MAAM;AACb,YAAM,IAAI3B,KAAJ,CAAU,wCAAV,CAAN;AACD;AAXI,GAAP;AAaD,CAtCM","sourcesContent":["/* global localStorage */\nimport type { MMKVConfiguration, NativeMMKV } from 'react-native-mmkv';\n\nconst canUseDOM =\n typeof window !== 'undefined' && window.document?.createElement != null;\n\nexport const createMMKV = (config: MMKVConfiguration): NativeMMKV => {\n if (config.id !== 'mmkv.default') {\n throw new Error(\"MMKV: 'id' is not supported on Web!\");\n }\n if (config.encryptionKey != null) {\n throw new Error(\"MMKV: 'encryptionKey' is not supported on Web!\");\n }\n if (config.path != null) {\n throw new Error(\"MMKV: 'path' is not supported on Web!\");\n }\n\n const storage = () => {\n if (!canUseDOM) {\n throw new Error(\n 'Tried to access storage on the server. Did you forget to call this in useEffect?'\n );\n }\n const domStorage =\n global?.localStorage ?? window?.localStorage ?? localStorage;\n if (domStorage == null) {\n throw new Error(`Could not find 'localStorage' instance!`);\n }\n return domStorage;\n };\n\n return {\n clearAll: () => storage().clear(),\n delete: (key) => storage().removeItem(key),\n set: (key, value) => storage().setItem(key, value.toString()),\n getString: (key) => storage().getItem(key) ?? undefined,\n getNumber: (key) => Number(storage().getItem(key) ?? 0),\n getBoolean: (key) => Boolean(storage().getItem(key) ?? false),\n getAllKeys: () => Object.keys(storage()),\n contains: (key) => storage().getItem(key) != null,\n recrypt: () => {\n throw new Error('`recrypt(..)` is not supported on Web!');\n },\n };\n};\n"]}
@@ -4,7 +4,9 @@ Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
6
  exports.useMMKV = useMMKV;
7
- exports.useMMKVNumber = exports.useMMKVBoolean = void 0;
7
+ exports.useMMKVBoolean = void 0;
8
+ exports.useMMKVListener = useMMKVListener;
9
+ exports.useMMKVNumber = void 0;
8
10
  exports.useMMKVObject = useMMKVObject;
9
11
  exports.useMMKVString = void 0;
10
12
 
@@ -44,7 +46,8 @@ function createMMKVHook(getter) {
44
46
  const mmkv = instance !== null && instance !== void 0 ? instance : getDefaultInstance();
45
47
  const [value, setValue] = (0, _react.useState)(() => getter(mmkv, key));
46
48
  const valueRef = (0, _react.useRef)(value);
47
- valueRef.current = value;
49
+ valueRef.current = value; // update value by user set
50
+
48
51
  const set = (0, _react.useCallback)(v => {
49
52
  const newValue = typeof v === 'function' ? v(valueRef.current) : v;
50
53
 
@@ -62,7 +65,16 @@ function createMMKVHook(getter) {
62
65
  default:
63
66
  throw new Error(`MMKV: Type ${typeof newValue} is not supported!`);
64
67
  }
65
- }, [key, mmkv]);
68
+ }, [key, mmkv]); // update value if key changes
69
+
70
+ const keyRef = (0, _react.useRef)(key);
71
+ (0, _react.useEffect)(() => {
72
+ if (key !== keyRef.current) {
73
+ setValue(getter(mmkv, key));
74
+ keyRef.current = key;
75
+ }
76
+ }, [key, mmkv]); // update value if it changes somewhere else (second hook, same key)
77
+
66
78
  (0, _react.useEffect)(() => {
67
79
  const listener = mmkv.addOnValueChangedListener(changedKey => {
68
80
  if (changedKey === key) {
@@ -145,4 +157,30 @@ function useMMKVObject(key, instance) {
145
157
  }, [setString]);
146
158
  return [value, setValue];
147
159
  }
160
+ /**
161
+ * Listen for changes in the given MMKV storage instance.
162
+ * If no instance is passed, the default instance will be used.
163
+ * @param valueChangedListener The function to call whenever a value inside the storage instance changes
164
+ * @param instance The instance to listen to changes to (or the default instance)
165
+ *
166
+ * @example
167
+ * ```ts
168
+ * useMMKVListener((key) => {
169
+ * console.log(`Value for "${key}" changed!`)
170
+ * })
171
+ * ```
172
+ */
173
+
174
+
175
+ function useMMKVListener(valueChangedListener, instance) {
176
+ const ref = (0, _react.useRef)(valueChangedListener);
177
+ ref.current = valueChangedListener;
178
+ const mmkv = instance !== null && instance !== void 0 ? instance : getDefaultInstance();
179
+ (0, _react.useEffect)(() => {
180
+ const listener = mmkv.addOnValueChangedListener(changedKey => {
181
+ ref.current(changedKey);
182
+ });
183
+ return () => listener.remove();
184
+ }, [mmkv]);
185
+ }
148
186
  //# sourceMappingURL=hooks.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["hooks.ts"],"names":["isConfigurationEqual","left","right","encryptionKey","id","path","defaultInstance","getDefaultInstance","MMKV","useMMKV","configuration","instance","lastConfiguration","current","createMMKVHook","getter","key","mmkv","value","setValue","valueRef","set","v","newValue","delete","Error","listener","addOnValueChangedListener","changedKey","remove","useMMKVString","getString","useMMKVNumber","getNumber","useMMKVBoolean","getBoolean","useMMKVObject","string","setString","undefined","JSON","parse","stringify"],"mappings":";;;;;;;;;;AAAA;;AAOA;;AAEA,SAASA,oBAAT,CACEC,IADF,EAEEC,KAFF,EAGW;AACT,SACED,IAAI,CAACE,aAAL,KAAuBD,KAAK,CAACC,aAA7B,IACAF,IAAI,CAACG,EAAL,KAAYF,KAAK,CAACE,EADlB,IAEAH,IAAI,CAACI,IAAL,KAAcH,KAAK,CAACG,IAHtB;AAKD;;AAED,IAAIC,eAA4B,GAAG,IAAnC;;AACA,SAASC,kBAAT,GAAoC;AAClC,MAAID,eAAe,IAAI,IAAvB,EAA6B;AAC3BA,IAAAA,eAAe,GAAG,IAAIE,UAAJ,EAAlB;AACD;;AACD,SAAOF,eAAP;AACD;;AAEM,SAASG,OAAT,CACLC,aADK,EAEkB;AACvB,QAAMC,QAAQ,GAAG,oBAAjB;AAEA,QAAMC,iBAAiB,GAAG,oBAA1B;;AACA,MACEA,iBAAiB,CAACC,OAAlB,IAA6B,IAA7B,IACA,CAACb,oBAAoB,CAACY,iBAAiB,CAACC,OAAnB,EAA4BH,aAA5B,CAFvB,EAGE;AACAE,IAAAA,iBAAiB,CAACC,OAAlB,GAA4BH,aAA5B;AACAC,IAAAA,QAAQ,CAACE,OAAT,GAAmB,IAAIL,UAAJ,CAASE,aAAT,CAAnB;AACD,GAVsB,CAYvB;;;AACA,SAAOC,QAAP;AACD;;AAED,SAASG,cAAT,CAIEC,MAJF,EAI8C;AAC5C,SAAO,CACLC,GADK,EAELL,QAFK,KAGiD;AACtD,UAAMM,IAAI,GAAGN,QAAH,aAAGA,QAAH,cAAGA,QAAH,GAAeJ,kBAAkB,EAA3C;AACA,UAAM,CAACW,KAAD,EAAQC,QAAR,IAAoB,qBAAS,MAAMJ,MAAM,CAACE,IAAD,EAAOD,GAAP,CAArB,CAA1B;AACA,UAAMI,QAAQ,GAAG,mBAAUF,KAAV,CAAjB;AACAE,IAAAA,QAAQ,CAACP,O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,GAAnB,CADyC,CAApC;AAGP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AACO,MAAMkB,cAAc,GAAGpB,cAAc,CAAC,CAACH,QAAD,EAAWK,GAAX,KAC3CL,QAAQ,CAACwB,UAAT,CAAoBnB,GAApB,CAD0C,CAArC;AAGP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;AACO,SAASoB,aAAT,CACLpB,GADK,EAELL,QAFK,EAG6D;AAClE,QAAM,CAAC0B,MAAD,EAASC,SAAT,IAAsBR,aAAa,CAACd,GAAD,EAAML,QAAN,CAAzC;AAEA,QAAMO,KAAK,GAAG,oBAAQ,MAAM;AAC1B,QAAImB,MAAM,IAAI,IAAd,EAAoB,OAAOE,SAAP;AACpB,WAAOC,IAAI,CAACC,KAAL,CAAWJ,MAAX,CAAP;AACD,GAHa,EAGX,CAACA,MAAD,CAHW,CAAd;AAIA,QAAMlB,QAAQ,GAAG,wBACdG,CAAD,IAAsB;AACpB,QAAIA,CAAC,IAAI,IAAT,EAAe;AACb;AACAgB,MAAAA,SAAS,CAACC,SAAD,CAAT;AACD,KAHD,MAGO;AACL;AACAD,MAAAA,SAAS,CAACE,IAAI,CAACE,SAAL,CAAepB,CAAf,CAAD,CAAT;AACD;AACF,GATc,EAUf,CAACgB,SAAD,CAVe,CAAjB;AAaA,SAAO,CAACpB,KAAD,EAAQC,QAAR,CAAP;AACD","sourcesContent":["import React, {\n useRef,\n useState,\n useMemo,\n useCallback,\n useEffect,\n} from 'react';\nimport { MMKV, MMKVConfiguration } from './MMKV';\n\nfunction isConfigurationEqual(\n left: MMKVConfiguration,\n right: MMKVConfiguration\n): boolean {\n return (\n left.encryptionKey === right.encryptionKey &&\n left.id === right.id &&\n left.path === right.path\n );\n}\n\nlet defaultInstance: MMKV | null = null;\nfunction getDefaultInstance(): MMKV {\n if (defaultInstance == null) {\n defaultInstance = new MMKV();\n }\n return defaultInstance;\n}\n\nexport function useMMKV(\n configuration: MMKVConfiguration\n): React.RefObject<MMKV> {\n const instance = useRef<MMKV>();\n\n const lastConfiguration = useRef<MMKVConfiguration>();\n if (\n lastConfiguration.current == null ||\n !isConfigurationEqual(lastConfiguration.current, configuration)\n ) {\n lastConfiguration.current = configuration;\n instance.current = new MMKV(configuration);\n }\n\n // @ts-expect-error it's not null, I promise.\n return instance;\n}\n\nfunction createMMKVHook<\n T extends boolean | number | (string | undefined),\n TSet extends T | undefined,\n TSetAction extends TSet | ((current: T) => TSet)\n>(getter: (instance: MMKV, key: string) => T) {\n return (\n key: string,\n instance?: MMKV\n ): [value: T, setValue: (value: TSetAction) => void] => {\n const mmkv = instance ?? getDefaultInstance();\n const [value, setValue] = useState(() => getter(mmkv, key));\n const valueRef = useRef<T>(value);\n valueRef.current = value;\n\n const set = useCallback(\n (v: TSetAction) => {\n const newValue = typeof v === 'function' ? v(valueRef.current) : v;\n switch (typeof newValue) {\n case 'number':\n case 'string':\n case 'boolean':\n mmkv.set(key, newValue);\n break;\n case 'undefined':\n mmkv.delete(key);\n break;\n default:\n throw new Error(`MMKV: Type ${typeof newValue} is not supported!`);\n }\n },\n [key, mmkv]\n );\n\n useEffect(() => {\n const listener = mmkv.addOnValueChangedListener((changedKey) => {\n if (changedKey === key) {\n setValue(getter(mmkv, key));\n }\n });\n return () => listener.remove();\n }, [key, mmkv]);\n\n return [value, set];\n };\n}\n\n/**\n * Use the string value of the given `key` from the given MMKV storage instance.\n *\n * If no instance is provided, a shared default instance will be used.\n *\n * @example\n * ```ts\n * const [username, setUsername] = useMMKVString(\"user.name\")\n * ```\n */\nexport const useMMKVString = createMMKVHook((instance, key) =>\n instance.getString(key)\n);\n\n/**\n * Use the number value of the given `key` from the given MMKV storage instance.\n *\n * If no instance is provided, a shared default instance will be used.\n *\n * @example\n * ```ts\n * const [age, setAge] = useMMKVNumber(\"user.age\")\n * ```\n */\nexport const useMMKVNumber = createMMKVHook((instance, key) =>\n instance.getNumber(key)\n);\n/**\n * Use the boolean value of the given `key` from the given MMKV storage instance.\n *\n * If no instance is provided, a shared default instance will be used.\n *\n * @example\n * ```ts\n * const [isPremiumAccount, setIsPremiumAccount] = useMMKVBoolean(\"user.isPremium\")\n * ```\n */\nexport const useMMKVBoolean = createMMKVHook((instance, key) =>\n instance.getBoolean(key)\n);\n/**\n * Use an object value of the given `key` from the given MMKV storage instance.\n *\n * If no instance is provided, a shared default instance will be used.\n *\n * The object will be serialized using `JSON`.\n *\n * @example\n * ```ts\n * const [user, setUser] = useMMKVObject<User>(\"user\")\n * ```\n */\nexport function useMMKVObject<T>(\n key: string,\n instance?: MMKV\n): [value: T | undefined, setValue: (value: T | undefined) => void] {\n const [string, setString] = useMMKVString(key, instance);\n\n const value = useMemo(() => {\n if (string == null) return undefined;\n return JSON.parse(string) as T;\n }, [string]);\n const setValue = useCallback(\n (v: T | undefined) => {\n if (v == null) {\n // Clear the Value\n setString(undefined);\n } else {\n // Store the Object as a serialized Value\n setString(JSON.stringify(v));\n }\n },\n [setString]\n );\n\n return [value, setValue];\n}\n"]}
1
+ {"version":3,"sources":["hooks.ts"],"names":["isConfigurationEqual","left","right","encryptionKey","id","path","defaultInstance","getDefaultInstance","MMKV","useMMKV","configuration","instance","lastConfiguration","current","createMMKVHook","getter","key","mmkv","value","setValue","valueRef","set","v","newValue","delete","Error","keyRef","listener","addOnValueChangedListener","changedKey","remove","useMMKVString","getString","useMMKVNumber","getNumber","useMMKVBoolean","getBoolean","useMMKVObject","string","setString","undefined","JSON","parse","stringify","useMMKVListener","valueChangedListener","ref"],"mappings":";;;;;;;;;;;;AAAA;;AAOA;;AAEA,SAASA,oBAAT,CACEC,IADF,EAEEC,KAFF,EAGW;AACT,SACED,IAAI,CAACE,aAAL,KAAuBD,KAAK,CAACC,aAA7B,IACAF,IAAI,CAACG,EAAL,KAAYF,KAAK,CAACE,EADlB,IAEAH,IAAI,CAACI,IAAL,KAAcH,KAAK,CAACG,IAHtB;AAKD;;AAED,IAAIC,eAA4B,GAAG,IAAn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AACW,yBAAL,CAAgCC,UAAD,IAAgB;AAC9DiB,MAAAA,GAAG,CAACjC,OAAJ,CAAYgB,UAAZ;AACD,KAFgB,CAAjB;AAGA,WAAO,MAAMF,QAAQ,CAACG,MAAT,EAAb;AACD,GALD,EAKG,CAACb,IAAD,CALH;AAMD","sourcesContent":["import React, {\n useRef,\n useState,\n useMemo,\n useCallback,\n useEffect,\n} from 'react';\nimport { MMKV, MMKVConfiguration } from './MMKV';\n\nfunction isConfigurationEqual(\n left: MMKVConfiguration,\n right: MMKVConfiguration\n): boolean {\n return (\n left.encryptionKey === right.encryptionKey &&\n left.id === right.id &&\n left.path === right.path\n );\n}\n\nlet defaultInstance: MMKV | null = null;\nfunction getDefaultInstance(): MMKV {\n if (defaultInstance == null) {\n defaultInstance = new MMKV();\n }\n return defaultInstance;\n}\n\nexport function useMMKV(\n configuration: MMKVConfiguration\n): React.RefObject<MMKV> {\n const instance = useRef<MMKV>();\n\n const lastConfiguration = useRef<MMKVConfiguration>();\n if (\n lastConfiguration.current == null ||\n !isConfigurationEqual(lastConfiguration.current, configuration)\n ) {\n lastConfiguration.current = configuration;\n instance.current = new MMKV(configuration);\n }\n\n // @ts-expect-error it's not null, I promise.\n return instance;\n}\n\nfunction createMMKVHook<\n T extends boolean | number | (string | undefined),\n TSet extends T | undefined,\n TSetAction extends TSet | ((current: T) => TSet)\n>(getter: (instance: MMKV, key: string) => T) {\n return (\n key: string,\n instance?: MMKV\n ): [value: T, setValue: (value: TSetAction) => void] => {\n const mmkv = instance ?? getDefaultInstance();\n const [value, setValue] = useState(() => getter(mmkv, key));\n const valueRef = useRef<T>(value);\n valueRef.current = value;\n\n // update value by user set\n const set = useCallback(\n (v: TSetAction) => {\n const newValue = typeof v === 'function' ? v(valueRef.current) : v;\n switch (typeof newValue) {\n case 'number':\n case 'string':\n case 'boolean':\n mmkv.set(key, newValue);\n break;\n case 'undefined':\n mmkv.delete(key);\n break;\n default:\n throw new Error(`MMKV: Type ${typeof newValue} is not supported!`);\n }\n },\n [key, mmkv]\n );\n\n // update value if key changes\n const keyRef = useRef(key);\n useEffect(() => {\n if (key !== keyRef.current) {\n setValue(getter(mmkv, key));\n keyRef.current = key;\n }\n }, [key, mmkv]);\n\n // update value if it changes somewhere else (second hook, same key)\n useEffect(() => {\n const listener = mmkv.addOnValueChangedListener((changedKey) => {\n if (changedKey === key) {\n setValue(getter(mmkv, key));\n }\n });\n return () => listener.remove();\n }, [key, mmkv]);\n\n return [value, set];\n };\n}\n\n/**\n * Use the string value of the given `key` from the given MMKV storage instance.\n *\n * If no instance is provided, a shared default instance will be used.\n *\n * @example\n * ```ts\n * const [username, setUsername] = useMMKVString(\"user.name\")\n * ```\n */\nexport const useMMKVString = createMMKVHook((instance, key) =>\n instance.getString(key)\n);\n\n/**\n * Use the number value of the given `key` from the given MMKV storage instance.\n *\n * If no instance is provided, a shared default instance will be used.\n *\n * @example\n * ```ts\n * const [age, setAge] = useMMKVNumber(\"user.age\")\n * ```\n */\nexport const useMMKVNumber = createMMKVHook((instance, key) =>\n instance.getNumber(key)\n);\n/**\n * Use the boolean value of the given `key` from the given MMKV storage instance.\n *\n * If no instance is provided, a shared default instance will be used.\n *\n * @example\n * ```ts\n * const [isPremiumAccount, setIsPremiumAccount] = useMMKVBoolean(\"user.isPremium\")\n * ```\n */\nexport const useMMKVBoolean = createMMKVHook((instance, key) =>\n instance.getBoolean(key)\n);\n/**\n * Use an object value of the given `key` from the given MMKV storage instance.\n *\n * If no instance is provided, a shared default instance will be used.\n *\n * The object will be serialized using `JSON`.\n *\n * @example\n * ```ts\n * const [user, setUser] = useMMKVObject<User>(\"user\")\n * ```\n */\nexport function useMMKVObject<T>(\n key: string,\n instance?: MMKV\n): [value: T | undefined, setValue: (value: T | undefined) => void] {\n const [string, setString] = useMMKVString(key, instance);\n\n const value = useMemo(() => {\n if (string == null) return undefined;\n return JSON.parse(string) as T;\n }, [string]);\n const setValue = useCallback(\n (v: T | undefined) => {\n if (v == null) {\n // Clear the Value\n setString(undefined);\n } else {\n // Store the Object as a serialized Value\n setString(JSON.stringify(v));\n }\n },\n [setString]\n );\n\n return [value, setValue];\n}\n\n/**\n * Listen for changes in the given MMKV storage instance.\n * If no instance is passed, the default instance will be used.\n * @param valueChangedListener The function to call whenever a value inside the storage instance changes\n * @param instance The instance to listen to changes to (or the default instance)\n *\n * @example\n * ```ts\n * useMMKVListener((key) => {\n * console.log(`Value for \"${key}\" changed!`)\n * })\n * ```\n */\nexport function useMMKVListener(\n valueChangedListener: (key: string) => void,\n instance?: MMKV\n): void {\n const ref = useRef(valueChangedListener);\n ref.current = valueChangedListener;\n\n const mmkv = instance ?? getDefaultInstance();\n\n useEffect(() => {\n const listener = mmkv.addOnValueChangedListener((changedKey) => {\n ref.current(changedKey);\n });\n return () => listener.remove();\n }, [mmkv]);\n}\n"]}
@@ -10,7 +10,7 @@ const onValueChangedListeners = new Map();
10
10
  export class MMKV {
11
11
  /**
12
12
  * Creates a new MMKV instance with the given Configuration.
13
- * If no custom `id` is supplied, `'default'` will be used.
13
+ * If no custom `id` is supplied, `'mmkv.default'` will be used.
14
14
  */
15
15
  constructor(configuration = {
16
16
  id: 'mmkv.default'
@@ -99,6 +99,21 @@ export class MMKV {
99
99
  return func();
100
100
  }
101
101
 
102
+ recrypt(key) {
103
+ const func = this.getFunctionFromCache('recrypt');
104
+ return func(key);
105
+ }
106
+
107
+ toString() {
108
+ return `MMKV (${this.id}): [${this.getAllKeys().join(', ')}]`;
109
+ }
110
+
111
+ toJSON() {
112
+ return {
113
+ [this.id]: this.getAllKeys()
114
+ };
115
+ }
116
+
102
117
  addOnValueChangedListener(onValueChanged) {
103
118
  this.onValueChangedListeners.push(onValueChanged);
104
119
  return {
@@ -1 +1 @@
1
- {"version":3,"sources":["MMKV.ts"],"names":["unstable_batchedUpdates","createMMKV","onValueChangedListeners","Map","MMKV","constructor","configuration","id","nativeInstance","functionCache","has","set","get","getFunctionFromCache","functionName","onValuesAboutToChange","keys","length","setImmediate","key","listener","value","func","getBoolean","getString","getNumber","contains","delete","getAllKeys","clearAll","addOnValueChangedListener","onValueChanged","push","remove","index","indexOf","splice"],"mappings":";;AAAA,SAASA,uBAAT,QAAwC,cAAxC;AACA,SAASC,UAAT,QAA2B,cAA3B;AA0GA,MAAMC,uBAAuB,GAAG,IAAIC,GAAJ,EAAhC;AAEA;AACA;AACA;;AACA,OAAO,MAAMC,IAAN,CAAoC;AAKzC;AACF;AACA;AACA;AACEC,EAAAA,WAAW,CAACC,aAAgC,GAAG;AAAEC,IAAAA,EAAE,EAAE;AAAN,GAApC,EAA4D;AAAA;;AAAA;;AAAA;;AACrE,SAAKA,EAAL,GAAUD,aAAa,CAACC,EAAxB;AACA,SAAKC,cAAL,GAAsBP,UAAU,CAACK,aAAD,CAAhC;AACA,SAAKG,aAAL,GAAqB,EAArB;AACD;;AAEkC,MAAvBP,uBAAuB,GAAG;AACpC,QAAI,CAACA,uBAAuB,CAACQ,GAAxB,CAA4B,KAAKH,EAAjC,CAAL,EAA2C;AACzCL,MAAAA,uBAAuB,CAACS,GAAxB,CAA4B,KAAKJ,EAAjC,EAAqC,EAArC;AACD;;AACD,WAAOL,uBAAuB,CAACU,GAAxB,CAA4B,KAAKL,EAAjC,CAAP;AACD;;AAEOM,EAAAA,oBAAoB,CAC1BC,YAD0B,EAEX;AACf,QAAI,KAAKL,aAAL,CAAmBK,YAAnB,KAAoC,IAAxC,EAA8C;AAC5C,WAAKL,aAAL,CAAmBK,YAAnB,IAAmC,KAAKN,cAAL,CAAoBM,YAApB,CAAnC;AACD;;AACD,WAAO,KAAKL,aAAL,CAAmBK,YAAnB,CAAP;AACD;;AAEOC,EAAAA,qBAAqB,CAACC,IAAD,EAAiB;AAC5C,QAAI,KAAKd,uBAAL,CAA6Be,MAA7B,KAAwC,CAA5C,EAA+C;AAE/CC,IAAAA,YAAY,CAAC,MAAM;AACjBlB,MAAAA,uBAAuB,CAAC,MAAM;AAC5B,aAAK,MAAMmB,GAAX,IAAkBH,IAAlB,EA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EAAX;AACD;;AACDO,EAAAA,QAAQ,GAAS;AACf,UAAMb,IAAI,GAAG,KAAKY,UAAL,EAAb;AACA,SAAKb,qBAAL,CAA2BC,IAA3B;AAEA,UAAMM,IAAI,GAAG,KAAKT,oBAAL,CAA0B,UAA1B,CAAb;AACA,WAAOS,IAAI,EAAX;AACD;;AAEDQ,EAAAA,yBAAyB,CAACC,cAAD,EAAkD;AACzE,SAAK7B,uBAAL,CAA6B8B,IAA7B,CAAkCD,cAAlC;AAEA,WAAO;AACLE,MAAAA,MAAM,EAAE,MAAM;AACZ,cAAMC,KAAK,GAAG,KAAKhC,uBAAL,CAA6BiC,OAA7B,CAAqCJ,cAArC,CAAd;;AACA,YAAIG,KAAK,KAAK,CAAC,CAAf,EAAkB;AAChB,eAAKhC,uBAAL,CAA6BkC,MAA7B,CAAoCF,KAApC,EAA2C,CAA3C;AACD;AACF;AANI,KAAP;AAQD;;AAhGwC","sourcesContent":["import { unstable_batchedUpdates } from 'react-native';\nimport { createMMKV } from './createMMKV';\n\ninterface Listener {\n remove: () => void;\n}\n\n/**\n * Used for configuration of a single MMKV instance.\n */\nexport interface MMKVConfiguration {\n /**\n * The MMKV instance's ID. If you want to use multiple instances, make sure to use different IDs!\n *\n * @example\n * ```ts\n * const userStorage = new MMKV({ id: `user-${userId}-storage` })\n * const globalStorage = new MMKV({ id: 'global-app-storage' })\n * ```\n *\n * @default 'mmkv.default'\n */\n id: string;\n /**\n * The MMKV instance's root path. By default, MMKV stores file inside `$(Documents)/mmkv/`. You can customize MMKV's root directory on MMKV initialization:\n *\n * @example\n * ```ts\n * const temporaryStorage = new MMKV({ path: '/tmp/' })\n * ```\n */\n path?: string;\n /**\n * 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.\n *\n * @example\n * ```ts\n * const secureStorage = new MMKV({ encryptionKey: 'my-encryption-key!' })\n * ```\n */\n encryptionKey?: string;\n}\n\n/**\n * Represents a single MMKV instance.\n */\ninterface MMKVInterface {\n /**\n * Set a value for the given `key`.\n */\n set: (key: string, value: boolean | string | number) => void;\n /**\n * Get a boolean value for the given `key`.\n *\n * @default false\n */\n getBoolean: (key: string) => boolean;\n /**\n * Get a string value for the given `key`.\n *\n * @default undefined\n */\n getString: (key: string) => string | undefined;\n /**\n * Get a number value for the given `key`.\n *\n * @default 0\n */\n getNumber: (key: string) => number;\n /**\n * Checks whether the given `key` is being stored in this MMKV instance.\n */\n contains: (key: string) => boolean;\n /**\n * Delete the given `key`.\n */\n delete: (key: string) => void;\n /**\n * Get all keys.\n *\n * @default []\n */\n getAllKeys: () => string[];\n /**\n * Delete all keys.\n */\n clearAll: () => void;\n /**\n * Adds a value changed listener.\n */\n addOnValueChangedListener: (\n onValueChanged: (key: string) => void\n ) => Listener;\n}\n\nexport type NativeMMKV = Pick<\n MMKVInterface,\n | 'clearAll'\n | 'contains'\n | 'delete'\n | 'getAllKeys'\n | 'getBoolean'\n | 'getNumber'\n | 'getString'\n | 'set'\n>;\n\nconst onValueChangedListeners = new Map<string, ((key: string) => void)[]>();\n\n/**\n * A single MMKV instance.\n */\nexport class MMKV implements MMKVInterface {\n private nativeInstance: NativeMMKV;\n private functionCache: Partial<NativeMMKV>;\n private id: string;\n\n /**\n * Creates a new MMKV instance with the given Configuration.\n * If no custom `id` is supplied, `'default'` will be used.\n */\n constructor(configuration: MMKVConfiguration = { id: 'mmkv.default' }) {\n this.id = configuration.id;\n this.nativeInstance = createMMKV(configuration);\n this.functionCache = {};\n }\n\n private get onValueChangedListeners() {\n if (!onValueChangedListeners.has(this.id)) {\n onValueChangedListeners.set(this.id, []);\n }\n return onValueChangedListeners.get(this.id)!;\n }\n\n private getFunctionFromCache<T extends keyof NativeMMKV>(\n functionName: T\n ): NativeMMKV[T] {\n if (this.functionCache[functionName] == null) {\n this.functionCache[functionName] = this.nativeInstance[functionName];\n }\n return this.functionCache[functionName] as NativeMMKV[T];\n }\n\n private onValuesAboutToChange(keys: string[]) {\n if (this.onValueChangedListeners.length === 0) return;\n\n setImmediate(() => {\n unstable_batchedUpdates(() => {\n for (const key of keys) {\n for (const listener of this.onValueChangedListeners) {\n listener(key);\n }\n }\n });\n });\n }\n\n set(key: string, value: boolean | string | number): void {\n this.onValuesAboutToChange([key]);\n\n const func = this.getFunctionFromCache('set');\n return func(key, value);\n }\n getBoolean(key: string): boolean {\n const func = this.getFunctionFromCache('getBoolean');\n return func(key);\n }\n getString(key: string): string | undefined {\n const func = this.getFunctionFromCache('getString');\n return func(key);\n }\n getNumber(key: string): number {\n const func = this.getFunctionFromCache('getNumber');\n return func(key);\n }\n contains(key: string): boolean {\n const func = this.getFunctionFromCache('contains');\n return func(key);\n }\n delete(key: string): void {\n this.onValuesAboutToChange([key]);\n\n const func = this.getFunctionFromCache('delete');\n return func(key);\n }\n getAllKeys(): string[] {\n const func = this.getFunctionFromCache('getAllKeys');\n return func();\n }\n clearAll(): void {\n const keys = this.getAllKeys();\n this.onValuesAboutToChange(keys);\n\n const func = this.getFunctionFromCache('clearAll');\n return func();\n }\n\n addOnValueChangedListener(onValueChanged: (key: string) => void): Listener {\n this.onValueChangedListeners.push(onValueChanged);\n\n return {\n remove: () => {\n const index = this.onValueChangedListeners.indexOf(onValueChanged);\n if (index !== -1) {\n this.onValueChangedListeners.splice(index, 1);\n }\n },\n };\n }\n}\n"]}
1
+ {"version":3,"sources":["MMKV.ts"],"names":["unstable_batchedUpdates","createMMKV","onValueChangedListeners","Map","MMKV","constructor","configuration","id","nativeInstance","functionCache","has","set","get","getFunctionFromCache","functionName","onValuesAboutToChange","keys","length","setImmediate","key","listener","value","func","getBoolean","getString","getNumber","contains","delete","getAllKeys","clearAll","recrypt","toString","join","toJSON","addOnValueChangedListener","onValueChanged","push","remove","index","indexOf","splice"],"mappings":";;AAAA,SAASA,uBAAT,QAAwC,cAAxC;AACA,SAASC,UAAT,QAA2B,cAA3B;AAwHA,MAAMC,uBAAuB,GAAG,I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OS,IAAI,EAAX;AACD;;AACDQ,EAAAA,OAAO,CAACX,GAAD,EAAgC;AACrC,UAAMG,IAAI,GAAG,KAAKT,oBAAL,CAA0B,SAA1B,CAAb;AACA,WAAOS,IAAI,CAACH,GAAD,CAAX;AACD;;AAEDY,EAAAA,QAAQ,GAAW;AACjB,WAAQ,SAAQ,KAAKxB,EAAG,OAAM,KAAKqB,UAAL,GAAkBI,IAAlB,CAAuB,IAAvB,CAA6B,GAA3D;AACD;;AACDC,EAAAA,MAAM,GAAW;AACf,WAAO;AACL,OAAC,KAAK1B,EAAN,GAAW,KAAKqB,UAAL;AADN,KAAP;AAGD;;AAEDM,EAAAA,yBAAyB,CAACC,cAAD,EAAkD;AACzE,SAAKjC,uBAAL,CAA6BkC,IAA7B,CAAkCD,cAAlC;AAEA,WAAO;AACLE,MAAAA,MAAM,EAAE,MAAM;AACZ,cAAMC,KAAK,GAAG,KAAKpC,uBAAL,CAA6BqC,OAA7B,CAAqCJ,cAArC,CAAd;;AACA,YAAIG,KAAK,KAAK,CAAC,CAAf,EAAkB;AAChB,eAAKpC,uBAAL,CAA6BsC,MAA7B,CAAoCF,KAApC,EAA2C,CAA3C;AACD;AACF;AANI,KAAP;AAQD;;AA7GwC","sourcesContent":["import { unstable_batchedUpdates } from 'react-native';\nimport { createMMKV } from './createMMKV';\n\ninterface Listener {\n remove: () => void;\n}\n\n/**\n * Used for configuration of a single MMKV instance.\n */\nexport interface MMKVConfiguration {\n /**\n * The MMKV instance's ID. If you want to use multiple instances, make sure to use different IDs!\n *\n * @example\n * ```ts\n * const userStorage = new MMKV({ id: `user-${userId}-storage` })\n * const globalStorage = new MMKV({ id: 'global-app-storage' })\n * ```\n *\n * @default 'mmkv.default'\n */\n id: string;\n /**\n * The MMKV instance's root path. By default, MMKV stores file inside `$(Documents)/mmkv/`. You can customize MMKV's root directory on MMKV initialization:\n *\n * @example\n * ```ts\n * const temporaryStorage = new MMKV({ path: '/tmp/' })\n * ```\n */\n path?: string;\n /**\n * 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.\n *\n * Encryption keys can have a maximum length of 16 bytes.\n *\n * @example\n * ```ts\n * const secureStorage = new MMKV({ encryptionKey: 'my-encryption-key!' })\n * ```\n */\n encryptionKey?: string;\n}\n\n/**\n * Represents a single MMKV instance.\n */\ninterface MMKVInterface {\n /**\n * Set a value for the given `key`.\n */\n set: (key: string, value: boolean | string | number) => void;\n /**\n * Get a boolean value for the given `key`.\n *\n * @default false\n */\n getBoolean: (key: string) => boolean;\n /**\n * Get a string value for the given `key`.\n *\n * @default undefined\n */\n getString: (key: string) => string | undefined;\n /**\n * Get a number value for the given `key`.\n *\n * @default 0\n */\n getNumber: (key: string) => number;\n /**\n * Checks whether the given `key` is being stored in this MMKV instance.\n */\n contains: (key: string) => boolean;\n /**\n * Delete the given `key`.\n */\n delete: (key: string) => void;\n /**\n * Get all keys.\n *\n * @default []\n */\n getAllKeys: () => string[];\n /**\n * Delete all keys.\n */\n clearAll: () => void;\n /**\n * Sets (or updates) the encryption-key to encrypt all data in this MMKV instance with.\n *\n * To remove encryption, pass `undefined` as a key.\n *\n * Encryption keys can have a maximum length of 16 bytes.\n */\n recrypt: (key: string | undefined) => void;\n /**\n * Adds a value changed listener. The Listener will be called whenever any value\n * in this storage instance changes (set or delete).\n *\n * To unsubscribe from value changes, call `remove()` on the Listener.\n */\n addOnValueChangedListener: (\n onValueChanged: (key: string) => void\n ) => Listener;\n}\n\nexport type NativeMMKV = Pick<\n MMKVInterface,\n | 'clearAll'\n | 'contains'\n | 'delete'\n | 'getAllKeys'\n | 'getBoolean'\n | 'getNumber'\n | 'getString'\n | 'set'\n | 'recrypt'\n>;\n\nconst onValueChangedListeners = new Map<string, ((key: string) => void)[]>();\n\n/**\n * A single MMKV instance.\n */\nexport class MMKV implements MMKVInterface {\n private nativeInstance: NativeMMKV;\n private functionCache: Partial<NativeMMKV>;\n private id: string;\n\n /**\n * Creates a new MMKV instance with the given Configuration.\n * If no custom `id` is supplied, `'mmkv.default'` will be used.\n */\n constructor(configuration: MMKVConfiguration = { id: 'mmkv.default' }) {\n this.id = configuration.id;\n this.nativeInstance = createMMKV(configuration);\n this.functionCache = {};\n }\n\n private get onValueChangedListeners() {\n if (!onValueChangedListeners.has(this.id)) {\n onValueChangedListeners.set(this.id, []);\n }\n return onValueChangedListeners.get(this.id)!;\n }\n\n private getFunctionFromCache<T extends keyof NativeMMKV>(\n functionName: T\n ): NativeMMKV[T] {\n if (this.functionCache[functionName] == null) {\n this.functionCache[functionName] = this.nativeInstance[functionName];\n }\n return this.functionCache[functionName] as NativeMMKV[T];\n }\n\n private onValuesAboutToChange(keys: string[]) {\n if (this.onValueChangedListeners.length === 0) return;\n\n setImmediate(() => {\n unstable_batchedUpdates(() => {\n for (const key of keys) {\n for (const listener of this.onValueChangedListeners) {\n listener(key);\n }\n }\n });\n });\n }\n\n set(key: string, value: boolean | string | number): void {\n this.onValuesAboutToChange([key]);\n\n const func = this.getFunctionFromCache('set');\n return func(key, value);\n }\n getBoolean(key: string): boolean {\n const func = this.getFunctionFromCache('getBoolean');\n return func(key);\n }\n getString(key: string): string | undefined {\n const func = this.getFunctionFromCache('getString');\n return func(key);\n }\n getNumber(key: string): number {\n const func = this.getFunctionFromCache('getNumber');\n return func(key);\n }\n contains(key: string): boolean {\n const func = this.getFunctionFromCache('contains');\n return func(key);\n }\n delete(key: string): void {\n this.onValuesAboutToChange([key]);\n\n const func = this.getFunctionFromCache('delete');\n return func(key);\n }\n getAllKeys(): string[] {\n const func = this.getFunctionFromCache('getAllKeys');\n return func();\n }\n clearAll(): void {\n const keys = this.getAllKeys();\n this.onValuesAboutToChange(keys);\n\n const func = this.getFunctionFromCache('clearAll');\n return func();\n }\n recrypt(key: string | undefined): void {\n const func = this.getFunctionFromCache('recrypt');\n return func(key);\n }\n\n toString(): string {\n return `MMKV (${this.id}): [${this.getAllKeys().join(', ')}]`;\n }\n toJSON(): object {\n return {\n [this.id]: this.getAllKeys(),\n };\n }\n\n addOnValueChangedListener(onValueChanged: (key: string) => void): Listener {\n this.onValueChangedListeners.push(onValueChanged);\n\n return {\n remove: () => {\n const index = this.onValueChangedListeners.indexOf(onValueChanged);\n if (index !== -1) {\n this.onValueChangedListeners.splice(index, 1);\n }\n },\n };\n }\n}\n"]}
@@ -51,7 +51,10 @@ export const createMMKV = config => {
51
51
  return Boolean((_storage$getItem3 = storage().getItem(key)) !== null && _storage$getItem3 !== void 0 ? _storage$getItem3 : false);
52
52
  },
53
53
  getAllKeys: () => Object.keys(storage()),
54
- contains: key => storage().getItem(key) != null
54
+ contains: key => storage().getItem(key) != null,
55
+ recrypt: () => {
56
+ throw new Error('`recrypt(..)` is not supported on Web!');
57
+ }
55
58
  };
56
59
  };
57
60
  //# sourceMappingURL=createMMKV.web.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["createMMKV.web.ts"],"names":["canUseDOM","window","document","createElement","createMMKV","config","id","Error","encryptionKey","path","storage","domStorage","global","localStorage","clearAll","clear","delete","key","removeItem","set","value","setItem","toString","getString","getItem","undefined","getNumber","Number","getBoolean","Boolean","getAllKeys","Object","keys","contains"],"mappings":";;AAAA;AAGA,MAAMA,SAAS,GACb,OAAOC,MAAP,KAAkB,WAAlB,IAAiC,qBAAAA,MAAM,CAACC,QAAP,sEAAiBC,aAAjB,KAAkC,IADrE;AAGA,OAAO,MAAMC,UAAU,GAAIC,MAAD,IAA2C;AACnE,MAAIA,MAAM,CAACC,EAAP,KAAc,cAAlB,EAAkC;AAChC,UAAM,IAAIC,KAAJ,CAAU,qCAAV,CAAN;AACD;;AACD,MAAIF,MAAM,CAACG,aAAP,IAAwB,IAA5B,EAAkC;AAChC,UAAM,IAAID,KAAJ,CAAU,gDAAV,CAAN;AACD;;AACD,MAAIF,MAAM,CAACI,IAAP,IAAe,IAAnB,EAAyB;AACvB,UAAM,IAAIF,KAAJ,CAAU,uCAAV,CAAN;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cesContent":["/* global localStorage */\nimport type { MMKVConfiguration, NativeMMKV } from 'react-native-mmkv';\n\nconst canUseDOM =\n typeof window !== 'undefined' && window.document?.createElement != null;\n\nexport const createMMKV = (config: MMKVConfiguration): NativeMMKV => {\n if (config.id !== 'mmkv.default') {\n throw new Error(\"MMKV: 'id' is not supported on Web!\");\n }\n if (config.encryptionKey != null) {\n throw new Error(\"MMKV: 'encryptionKey' is not supported on Web!\");\n }\n if (config.path != null) {\n throw new Error(\"MMKV: 'path' is not supported on Web!\");\n }\n\n const storage = () => {\n if (!canUseDOM) {\n throw new Error(\n 'Tried to access storage on the server. Did you forget to call this in useEffect?'\n );\n }\n const domStorage =\n global?.localStorage ?? window?.localStorage ?? localStorage;\n if (domStorage == null) {\n throw new Error(`Could not find 'localStorage' instance!`);\n }\n return domStorage;\n };\n\n return {\n clearAll: () => storage().clear(),\n delete: (key) => storage().removeItem(key),\n set: (key, value) => storage().setItem(key, value.toString()),\n getString: (key) => storage().getItem(key) ?? undefined,\n getNumber: (key) => Number(storage().getItem(key) ?? 0),\n getBoolean: (key) => Boolean(storage().getItem(key) ?? false),\n getAllKeys: () => Object.keys(storage()),\n contains: (key) => storage().getItem(key) != null,\n };\n};\n"]}
1
+ {"version":3,"sources":["createMMKV.web.ts"],"names":["canUseDOM","window","document","createElement","createMMKV","config","id","Error","encryptionKey","path","storage","domStorage","global","localStorage","clearAll","clear","delete","key","removeItem","set","value","setItem","toString","getString","getItem","undefined","getNumber","Number","getBoolean","Boolean","getAllKeys","Object","keys","contains","recrypt"],"mappings":";;AAAA;AAGA,MAAMA,SAAS,GACb,OAAOC,MAAP,KAAkB,WAAlB,IAAiC,qBAAAA,MAAM,CAACC,QAAP,sEAAiBC,aAAjB,KAAkC,IADrE;AAGA,OAAO,MAAMC,UAAU,GAAIC,MAAD,IAA2C;AACnE,MAAIA,MAAM,CAACC,EAAP,KAAc,cAAlB,EAAkC;AAChC,UAAM,IAAIC,KAAJ,CAAU,qCAAV,CAAN;AACD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AA,KANP;AAOLa,IAAAA,UAAU,EAAE,MAAMC,MAAM,CAACC,IAAP,CAAYtB,OAAO,EAAnB,CAPb;AAQLuB,IAAAA,QAAQ,EAAGhB,GAAD,IAASP,OAAO,GAAGc,OAAV,CAAkBP,GAAlB,KAA0B,IARxC;AASLiB,IAAAA,OAAO,EAAE,MAAM;AACb,YAAM,IAAI3B,KAAJ,CAAU,wCAAV,CAAN;AACD;AAXI,GAAP;AAaD,CAtCM","sourcesContent":["/* global localStorage */\nimport type { MMKVConfiguration, NativeMMKV } from 'react-native-mmkv';\n\nconst canUseDOM =\n typeof window !== 'undefined' && window.document?.createElement != null;\n\nexport const createMMKV = (config: MMKVConfiguration): NativeMMKV => {\n if (config.id !== 'mmkv.default') {\n throw new Error(\"MMKV: 'id' is not supported on Web!\");\n }\n if (config.encryptionKey != null) {\n throw new Error(\"MMKV: 'encryptionKey' is not supported on Web!\");\n }\n if (config.path != null) {\n throw new Error(\"MMKV: 'path' is not supported on Web!\");\n }\n\n const storage = () => {\n if (!canUseDOM) {\n throw new Error(\n 'Tried to access storage on the server. Did you forget to call this in useEffect?'\n );\n }\n const domStorage =\n global?.localStorage ?? window?.localStorage ?? localStorage;\n if (domStorage == null) {\n throw new Error(`Could not find 'localStorage' instance!`);\n }\n return domStorage;\n };\n\n return {\n clearAll: () => storage().clear(),\n delete: (key) => storage().removeItem(key),\n set: (key, value) => storage().setItem(key, value.toString()),\n getString: (key) => storage().getItem(key) ?? undefined,\n getNumber: (key) => Number(storage().getItem(key) ?? 0),\n getBoolean: (key) => Boolean(storage().getItem(key) ?? false),\n getAllKeys: () => Object.keys(storage()),\n contains: (key) => storage().getItem(key) != null,\n recrypt: () => {\n throw new Error('`recrypt(..)` is not supported on Web!');\n },\n };\n};\n"]}
@@ -33,7 +33,8 @@ function createMMKVHook(getter) {
33
33
  const mmkv = instance !== null && instance !== void 0 ? instance : getDefaultInstance();
34
34
  const [value, setValue] = useState(() => getter(mmkv, key));
35
35
  const valueRef = useRef(value);
36
- valueRef.current = value;
36
+ valueRef.current = value; // update value by user set
37
+
37
38
  const set = useCallback(v => {
38
39
  const newValue = typeof v === 'function' ? v(valueRef.current) : v;
39
40
 
@@ -51,7 +52,16 @@ function createMMKVHook(getter) {
51
52
  default:
52
53
  throw new Error(`MMKV: Type ${typeof newValue} is not supported!`);
53
54
  }
54
- }, [key, mmkv]);
55
+ }, [key, mmkv]); // update value if key changes
56
+
57
+ const keyRef = useRef(key);
58
+ useEffect(() => {
59
+ if (key !== keyRef.current) {
60
+ setValue(getter(mmkv, key));
61
+ keyRef.current = key;
62
+ }
63
+ }, [key, mmkv]); // update value if it changes somewhere else (second hook, same key)
64
+
55
65
  useEffect(() => {
56
66
  const listener = mmkv.addOnValueChangedListener(changedKey => {
57
67
  if (changedKey === key) {
@@ -130,4 +140,29 @@ export function useMMKVObject(key, instance) {
130
140
  }, [setString]);
131
141
  return [value, setValue];
132
142
  }
143
+ /**
144
+ * Listen for changes in the given MMKV storage instance.
145
+ * If no instance is passed, the default instance will be used.
146
+ * @param valueChangedListener The function to call whenever a value inside the storage instance changes
147
+ * @param instance The instance to listen to changes to (or the default instance)
148
+ *
149
+ * @example
150
+ * ```ts
151
+ * useMMKVListener((key) => {
152
+ * console.log(`Value for "${key}" changed!`)
153
+ * })
154
+ * ```
155
+ */
156
+
157
+ export function useMMKVListener(valueChangedListener, instance) {
158
+ const ref = useRef(valueChangedListener);
159
+ ref.current = valueChangedListener;
160
+ const mmkv = instance !== null && instance !== void 0 ? instance : getDefaultInstance();
161
+ useEffect(() => {
162
+ const listener = mmkv.addOnValueChangedListener(changedKey => {
163
+ ref.current(changedKey);
164
+ });
165
+ return () => listener.remove();
166
+ }, [mmkv]);
167
+ }
133
168
  //# sourceMappingURL=hooks.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["hooks.ts"],"names":["useRef","useState","useMemo","useCallback","useEffect","MMKV","isConfigurationEqual","left","right","encryptionKey","id","path","defaultInstance","getDefaultInstance","useMMKV","configuration","instance","lastConfiguration","current","createMMKVHook","getter","key","mmkv","value","setValue","valueRef","set","v","newValue","delete","Error","listener","addOnValueChangedListener","changedKey","remove","useMMKVString","getString","useMMKVNumber","getNumber","useMMKVBoolean","getBoolean","useMMKVObject","string","setString","undefined","JSON","parse","stringify"],"mappings":"AAAA,SACEA,MADF,EAEEC,QAFF,EAGEC,OAHF,EAIEC,WAJF,EAKEC,SALF,QAMO,OANP;AAOA,SAASC,IAAT,QAAwC,QAAxC;;AAEA,SAASC,oBAAT,CACEC,IADF,EAEEC,KAFF,EAGW;AACT,SACED,IAAI,CAACE,aAAL,KAAuBD,KAAK,CAACC,aAA7B,IACAF,IAAI,CAACG,EAAL,KAAYF,KAAK,CAACE,EADlB,IAEAH,IAAI,CAACI,IAAL,KAAcH,KAAK,CAACG,IAHtB;AAKD;;AAED,IAAIC,eAA4B,GAAG,IAAnC;;AACA,SAASC,kBAAT,GAAoC;AAClC,MAAID,eAAe,IAAI,IAAvB,EAA6B;AAC3BA,IAAAA,eAAe,GAAG,IAAIP,IAAJ,EAAlB;AACD;;AACD,SAAOO,eAAP;AACD;;AAED,OAAO,SAASE,OAAT,CACLC,aADK,EAEkB;AACvB,QAAMC,QAAQ,GAAGhB,MAAM,EAAvB;AAEA,QAAMiB,iBAAiB,GAAGjB,MAAM,EAAhC;;AACA,MACEiB,iBAAiB,CAACC,OAAlB,IAA6B,IAA7B,IACA,CAACZ,oBAAoB,CAACW,iBAAiB,CAACC,OAAnB,EAA4BH,aAA5B,CAFvB,EAGE;AACAE,IAAAA,iBAAiB,CAACC,OAAlB,GAA4BH,aAA5B;AACAC,IAAAA,QAAQ,CAACE,OAAT,GAAmB,IAAIb,IAAJ,CAASU,aAAT,CAAnB;AACD,GAVsB,CAYvB;;;AACA,SAAOC,QAAP;AACD;;AAED,SAASG,cAAT,CAIEC,MAJF,EAI8C;AAC5C,SAAO,CACLC,GADK,EAELL,QAFK,KAGiD;AACtD,UAAMM,IAAI,GAAGN,QAAH,aAAGA,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useState,\n useMemo,\n useCallback,\n useEffect,\n} from 'react';\nimport { MMKV, MMKVConfiguration } from './MMKV';\n\nfunction isConfigurationEqual(\n left: MMKVConfiguration,\n right: MMKVConfiguration\n): boolean {\n return (\n left.encryptionKey === right.encryptionKey &&\n left.id === right.id &&\n left.path === right.path\n );\n}\n\nlet defaultInstance: MMKV | null = null;\nfunction getDefaultInstance(): MMKV {\n if (defaultInstance == null) {\n defaultInstance = new MMKV();\n }\n return defaultInstance;\n}\n\nexport function useMMKV(\n configuration: MMKVConfiguration\n): React.RefObject<MMKV> {\n const instance = useRef<MMKV>();\n\n const lastConfiguration = useRef<MMKVConfiguration>();\n if (\n lastConfiguration.current == null ||\n !isConfigurationEqual(lastConfiguration.current, configuration)\n ) {\n lastConfiguration.current = configuration;\n instance.current = new MMKV(configuration);\n }\n\n // @ts-expect-error it's not null, I promise.\n return instance;\n}\n\nfunction createMMKVHook<\n T extends boolean | number | (string | undefined),\n TSet extends T | undefined,\n TSetAction extends TSet | ((current: T) => TSet)\n>(getter: (instance: MMKV, key: string) => T) {\n return (\n key: string,\n instance?: MMKV\n ): [value: T, setValue: (value: TSetAction) => void] => {\n const mmkv = instance ?? getDefaultInstance();\n const [value, setValue] = useState(() => getter(mmkv, key));\n const valueRef = useRef<T>(value);\n valueRef.current = value;\n\n const set = useCallback(\n (v: TSetAction) => {\n const newValue = typeof v === 'function' ? v(valueRef.current) : v;\n switch (typeof newValue) {\n case 'number':\n case 'string':\n case 'boolean':\n mmkv.set(key, newValue);\n break;\n case 'undefined':\n mmkv.delete(key);\n break;\n default:\n throw new Error(`MMKV: Type ${typeof newValue} is not supported!`);\n }\n },\n [key, mmkv]\n );\n\n useEffect(() => {\n const listener = mmkv.addOnValueChangedListener((changedKey) => {\n if (changedKey === key) {\n setValue(getter(mmkv, key));\n }\n });\n return () => listener.remove();\n }, [key, mmkv]);\n\n return [value, set];\n };\n}\n\n/**\n * Use the string value of the given `key` from the given MMKV storage instance.\n *\n * If no instance is provided, a shared default instance will be used.\n *\n * @example\n * ```ts\n * const [username, setUsername] = useMMKVString(\"user.name\")\n * ```\n */\nexport const useMMKVString = createMMKVHook((instance, key) =>\n instance.getString(key)\n);\n\n/**\n * Use the number value of the given `key` from the given MMKV storage instance.\n *\n * If no instance is provided, a shared default instance will be used.\n *\n * @example\n * ```ts\n * const [age, setAge] = useMMKVNumber(\"user.age\")\n * ```\n */\nexport const useMMKVNumber = createMMKVHook((instance, key) =>\n instance.getNumber(key)\n);\n/**\n * Use the boolean value of the given `key` from the given MMKV storage instance.\n *\n * If no instance is provided, a shared default instance will be used.\n *\n * @example\n * ```ts\n * const [isPremiumAccount, setIsPremiumAccount] = useMMKVBoolean(\"user.isPremium\")\n * ```\n */\nexport const useMMKVBoolean = createMMKVHook((instance, key) =>\n instance.getBoolean(key)\n);\n/**\n * Use an object value of the given `key` from the given MMKV storage instance.\n *\n * If no instance is provided, a shared default instance will be used.\n *\n * The object will be serialized using `JSON`.\n *\n * @example\n * ```ts\n * const [user, setUser] = useMMKVObject<User>(\"user\")\n * ```\n */\nexport function useMMKVObject<T>(\n key: string,\n instance?: MMKV\n): [value: T | undefined, setValue: (value: T | undefined) => void] {\n const [string, setString] = useMMKVString(key, instance);\n\n const value = useMemo(() => {\n if (string == null) return undefined;\n return JSON.parse(string) as T;\n }, [string]);\n const setValue = useCallback(\n (v: T | undefined) => {\n if (v == null) {\n // Clear the Value\n setString(undefined);\n } else {\n // Store the Object as a serialized Value\n setString(JSON.stringify(v));\n }\n },\n [setString]\n );\n\n return [value, setValue];\n}\n"]}
1
+ {"version":3,"sources":["hooks.ts"],"names":["useRef","useState","useMemo","useCallback","useEffect","MMKV","isConfigurationEqual","left","right","encryptionKey","id","path","defaultInstance","getDefaultInstance","useMMKV","configuration","instance","lastConfiguration","current","createMMKVHook","getter","key","mmkv","value","setValue","valueRef","set","v","newValue","delete","Error","keyRef","listener","addOnValueChangedListener","changedKey","remove","useMMKVString","getString","useMMKVNumber","getNumber","useMMKVBoolean","getBoolean","useMMKVObject","string","setString","undefined","JSON","parse","stringify","useMMKVListener","valueChangedListener","ref"],"mappings":"AAAA,SACEA,MADF,EAEEC,QAFF,EAGEC,OAHF,EAIEC,WAJF,EAKEC,SALF,QAMO,OANP;AAOA,SAASC,IAAT,QAAwC,QAAxC;;AAEA,SAASC,oBAAT,CACEC,IADF,EAEEC,KAFF,EAGW;AACT,SACED,IAAI,CAACE,aAAL,KAAuBD,KAAK,CAACC,aAA7B,IACAF,IAAI,CAACG,EAAL,KAAYF,KAAK,CAACE,EADlB,IAEAH,IAAI,CAACI,IAAL,KAAcH,KAAK,CAACG,IAHtB;AAKD;;AAED,IAAIC,eAA4B,GAAG,IAAnC;;AACA,SAASC,kBAAT,GAAoC;AAClC,MAAID,eAAe,IAAI,IAAvB,EAA6B;AAC3BA,IAAAA,eAAe,GAAG,IAAIP,IAAJ,EAAlB;AACD;;AACD,SAAOO,eAAP;AACD;;AAED,OAAO,SAASE,OAAT,CACLC,aADK,EAEkB;AACvB,QAAMC,QAAQ,GAAGhB,MAAM,EAAvB;AAEA,QAAMiB,iBAAiB,GAAGjB,MAAM,EAAhC;;AACA,MACEiB,iBAAiB,CAACC,OAAlB,IAA6B,IAA7B,IACA,CAACZ,oBAAoB,CAACW,iBAAiB,CAACC,OAAnB,EAA4BH,aAA5B,CAFvB,EAGE;AACAE,IAAAA,iBAAiB,CAACC,OAAlB,GAA4BH,aAA5B;AACAC,IAAAA,QAAQ,CAACE,OAAT,GAAmB,IAAIb,IAAJ,CAASU,aAAT,CAAnB;AACD,GAVsB,CAYvB;;;AACA,SAAOC,QAAP;AACD;;AAED,SAASG,cAAT,CAIEC,MAJF,EAI8C;AAC5C,SAAO,CACLC,GADK,EAELL,QAFK,KAGiD;AACtD,UAAMM,IAAI,GAAGN,QAAH,aAAGA,QAAH,cAAGA,QAAH,GAAeH,kBAAkB,EAA3C;AACA,UAAM,CAACU,KAAD,EAAQC,QAAR,IAAoBvB,QAAQ,CAAC,MAAMmB,MAA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iB,MAAAA,SAAS,CAACC,SAAD,CAAT;AACD,KAHD,MAGO;AACL;AACAD,MAAAA,SAAS,CAACE,IAAI,CAACE,SAAL,CAAerB,CAAf,CAAD,CAAT;AACD;AACF,GATyB,EAU1B,CAACiB,SAAD,CAV0B,CAA5B;AAaA,SAAO,CAACrB,KAAD,EAAQC,QAAR,CAAP;AACD;AAED;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AACA,OAAO,SAASyB,eAAT,CACLC,oBADK,EAELlC,QAFK,EAGC;AACN,QAAMmC,GAAG,GAAGnD,MAAM,CAACkD,oBAAD,CAAlB;AACAC,EAAAA,GAAG,CAACjC,OAAJ,GAAcgC,oBAAd;AAEA,QAAM5B,IAAI,GAAGN,QAAH,aAAGA,QAAH,cAAGA,QAAH,GAAeH,kBAAkB,EAA3C;AAEAT,EAAAA,SAAS,CAAC,MAAM;AACd,UAAM4B,QAAQ,GAAGV,IAAI,CAACW,yBAAL,CAAgCC,UAAD,IAAgB;AAC9DiB,MAAAA,GAAG,CAACjC,OAAJ,CAAYgB,UAAZ;AACD,KAFgB,CAAjB;AAGA,WAAO,MAAMF,QAAQ,CAACG,MAAT,EAAb;AACD,GALQ,EAKN,CAACb,IAAD,CALM,CAAT;AAMD","sourcesContent":["import React, {\n useRef,\n useState,\n useMemo,\n useCallback,\n useEffect,\n} from 'react';\nimport { MMKV, MMKVConfiguration } from './MMKV';\n\nfunction isConfigurationEqual(\n left: MMKVConfiguration,\n right: MMKVConfiguration\n): boolean {\n return (\n left.encryptionKey === right.encryptionKey &&\n left.id === right.id &&\n left.path === right.path\n );\n}\n\nlet defaultInstance: MMKV | null = null;\nfunction getDefaultInstance(): MMKV {\n if (defaultInstance == null) {\n defaultInstance = new MMKV();\n }\n return defaultInstance;\n}\n\nexport function useMMKV(\n configuration: MMKVConfiguration\n): React.RefObject<MMKV> {\n const instance = useRef<MMKV>();\n\n const lastConfiguration = useRef<MMKVConfiguration>();\n if (\n lastConfiguration.current == null ||\n !isConfigurationEqual(lastConfiguration.current, configuration)\n ) {\n lastConfiguration.current = configuration;\n instance.current = new MMKV(configuration);\n }\n\n // @ts-expect-error it's not null, I promise.\n return instance;\n}\n\nfunction createMMKVHook<\n T extends boolean | number | (string | undefined),\n TSet extends T | undefined,\n TSetAction extends TSet | ((current: T) => TSet)\n>(getter: (instance: MMKV, key: string) => T) {\n return (\n key: string,\n instance?: MMKV\n ): [value: T, setValue: (value: TSetAction) => void] => {\n const mmkv = instance ?? getDefaultInstance();\n const [value, setValue] = useState(() => getter(mmkv, key));\n const valueRef = useRef<T>(value);\n valueRef.current = value;\n\n // update value by user set\n const set = useCallback(\n (v: TSetAction) => {\n const newValue = typeof v === 'function' ? v(valueRef.current) : v;\n switch (typeof newValue) {\n case 'number':\n case 'string':\n case 'boolean':\n mmkv.set(key, newValue);\n break;\n case 'undefined':\n mmkv.delete(key);\n break;\n default:\n throw new Error(`MMKV: Type ${typeof newValue} is not supported!`);\n }\n },\n [key, mmkv]\n );\n\n // update value if key changes\n const keyRef = useRef(key);\n useEffect(() => {\n if (key !== keyRef.current) {\n setValue(getter(mmkv, key));\n keyRef.current = key;\n }\n }, [key, mmkv]);\n\n // update value if it changes somewhere else (second hook, same key)\n useEffect(() => {\n const listener = mmkv.addOnValueChangedListener((changedKey) => {\n if (changedKey === key) {\n setValue(getter(mmkv, key));\n }\n });\n return () => listener.remove();\n }, [key, mmkv]);\n\n return [value, set];\n };\n}\n\n/**\n * Use the string value of the given `key` from the given MMKV storage instance.\n *\n * If no instance is provided, a shared default instance will be used.\n *\n * @example\n * ```ts\n * const [username, setUsername] = useMMKVString(\"user.name\")\n * ```\n */\nexport const useMMKVString = createMMKVHook((instance, key) =>\n instance.getString(key)\n);\n\n/**\n * Use the number value of the given `key` from the given MMKV storage instance.\n *\n * If no instance is provided, a shared default instance will be used.\n *\n * @example\n * ```ts\n * const [age, setAge] = useMMKVNumber(\"user.age\")\n * ```\n */\nexport const useMMKVNumber = createMMKVHook((instance, key) =>\n instance.getNumber(key)\n);\n/**\n * Use the boolean value of the given `key` from the given MMKV storage instance.\n *\n * If no instance is provided, a shared default instance will be used.\n *\n * @example\n * ```ts\n * const [isPremiumAccount, setIsPremiumAccount] = useMMKVBoolean(\"user.isPremium\")\n * ```\n */\nexport const useMMKVBoolean = createMMKVHook((instance, key) =>\n instance.getBoolean(key)\n);\n/**\n * Use an object value of the given `key` from the given MMKV storage instance.\n *\n * If no instance is provided, a shared default instance will be used.\n *\n * The object will be serialized using `JSON`.\n *\n * @example\n * ```ts\n * const [user, setUser] = useMMKVObject<User>(\"user\")\n * ```\n */\nexport function useMMKVObject<T>(\n key: string,\n instance?: MMKV\n): [value: T | undefined, setValue: (value: T | undefined) => void] {\n const [string, setString] = useMMKVString(key, instance);\n\n const value = useMemo(() => {\n if (string == null) return undefined;\n return JSON.parse(string) as T;\n }, [string]);\n const setValue = useCallback(\n (v: T | undefined) => {\n if (v == null) {\n // Clear the Value\n setString(undefined);\n } else {\n // Store the Object as a serialized Value\n setString(JSON.stringify(v));\n }\n },\n [setString]\n );\n\n return [value, setValue];\n}\n\n/**\n * Listen for changes in the given MMKV storage instance.\n * If no instance is passed, the default instance will be used.\n * @param valueChangedListener The function to call whenever a value inside the storage instance changes\n * @param instance The instance to listen to changes to (or the default instance)\n *\n * @example\n * ```ts\n * useMMKVListener((key) => {\n * console.log(`Value for \"${key}\" changed!`)\n * })\n * ```\n */\nexport function useMMKVListener(\n valueChangedListener: (key: string) => void,\n instance?: MMKV\n): void {\n const ref = useRef(valueChangedListener);\n ref.current = valueChangedListener;\n\n const mmkv = instance ?? getDefaultInstance();\n\n useEffect(() => {\n const listener = mmkv.addOnValueChangedListener((changedKey) => {\n ref.current(changedKey);\n });\n return () => listener.remove();\n }, [mmkv]);\n}\n"]}
@@ -29,6 +29,8 @@ export interface MMKVConfiguration {
29
29
  /**
30
30
  * 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.
31
31
  *
32
+ * Encryption keys can have a maximum length of 16 bytes.
33
+ *
32
34
  * @example
33
35
  * ```ts
34
36
  * const secureStorage = new MMKV({ encryptionKey: 'my-encryption-key!' })
@@ -81,11 +83,22 @@ interface MMKVInterface {
81
83
  */
82
84
  clearAll: () => void;
83
85
  /**
84
- * Adds a value changed listener.
86
+ * Sets (or updates) the encryption-key to encrypt all data in this MMKV instance with.
87
+ *
88
+ * To remove encryption, pass `undefined` as a key.
89
+ *
90
+ * Encryption keys can have a maximum length of 16 bytes.
91
+ */
92
+ recrypt: (key: string | undefined) => void;
93
+ /**
94
+ * Adds a value changed listener. The Listener will be called whenever any value
95
+ * in this storage instance changes (set or delete).
96
+ *
97
+ * To unsubscribe from value changes, call `remove()` on the Listener.
85
98
  */
86
99
  addOnValueChangedListener: (onValueChanged: (key: string) => void) => Listener;
87
100
  }
88
- export declare type NativeMMKV = Pick<MMKVInterface, 'clearAll' | 'contains' | 'delete' | 'getAllKeys' | 'getBoolean' | 'getNumber' | 'getString' | 'set'>;
101
+ export declare type NativeMMKV = Pick<MMKVInterface, 'clearAll' | 'contains' | 'delete' | 'getAllKeys' | 'getBoolean' | 'getNumber' | 'getString' | 'set' | 'recrypt'>;
89
102
  /**
90
103
  * A single MMKV instance.
91
104
  */
@@ -95,7 +108,7 @@ export declare class MMKV implements MMKVInterface {
95
108
  private id;
96
109
  /**
97
110
  * Creates a new MMKV instance with the given Configuration.
98
- * If no custom `id` is supplied, `'default'` will be used.
111
+ * If no custom `id` is supplied, `'mmkv.default'` will be used.
99
112
  */
100
113
  constructor(configuration?: MMKVConfiguration);
101
114
  private get onValueChangedListeners();
@@ -109,6 +122,9 @@ export declare class MMKV implements MMKVInterface {
109
122
  delete(key: string): void;
110
123
  getAllKeys(): string[];
111
124
  clearAll(): void;
125
+ recrypt(key: string | undefined): void;
126
+ toString(): string;
127
+ toJSON(): object;
112
128
  addOnValueChangedListener(onValueChanged: (key: string) => void): Listener;
113
129
  }
114
130
  export {};
@@ -47,3 +47,17 @@ export declare const useMMKVBoolean: (key: string, instance?: MMKV | undefined)
47
47
  * ```
48
48
  */
49
49
  export declare function useMMKVObject<T>(key: string, instance?: MMKV): [value: T | undefined, setValue: (value: T | undefined) => void];
50
+ /**
51
+ * Listen for changes in the given MMKV storage instance.
52
+ * If no instance is passed, the default instance will be used.
53
+ * @param valueChangedListener The function to call whenever a value inside the storage instance changes
54
+ * @param instance The instance to listen to changes to (or the default instance)
55
+ *
56
+ * @example
57
+ * ```ts
58
+ * useMMKVListener((key) => {
59
+ * console.log(`Value for "${key}" changed!`)
60
+ * })
61
+ * ```
62
+ */
63
+ export declare function useMMKVListener(valueChangedListener: (key: string) => void, instance?: MMKV): void;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-native-mmkv",
3
- "version": "2.0.1",
3
+ "version": "2.1.2",
4
4
  "description": "The fastest key/value storage for React Native. ~30x faster than AsyncStorage! Works on Android, iOS and Web.",
5
5
  "main": "lib/commonjs/index",
6
6
  "module": "lib/module/index",
@@ -91,7 +91,31 @@
91
91
  },
92
92
  "plugins": {
93
93
  "@release-it/conventional-changelog": {
94
- "preset": "angular"
94
+ "preset": {
95
+ "name": "conventionalcommits",
96
+ "types": [
97
+ {
98
+ "type": "feat",
99
+ "section": "✨ Features"
100
+ },
101
+ {
102
+ "type": "fix",
103
+ "section": "🐛 Bug Fixes"
104
+ },
105
+ {
106
+ "type": "perf",
107
+ "section": "💨 Performance Improvements"
108
+ },
109
+ {
110
+ "type": "chore(deps)",
111
+ "section": "🛠️ Dependency Upgrades"
112
+ },
113
+ {
114
+ "type": "docs",
115
+ "section": "📚 Documentation"
116
+ }
117
+ ]
118
+ }
95
119
  }
96
120
  }
97
121
  },
@@ -10,7 +10,7 @@ Pod::Spec.new do |s|
10
10
  s.license = package["license"]
11
11
  s.authors = package["author"]
12
12
 
13
- s.platforms = { :ios => "11.0", :tvos => "12.0" }
13
+ s.platforms = { :ios => "11.0", :tvos => "12.0", :osx => "10.14" }
14
14
  s.source = { :git => "https://github.com/mrousavy/react-native-mmkv.git", :tag => "#{s.version}" }
15
15
 
16
16
  # All source files that should be publicly visible