Skip to content

Commit 47804cf

Browse files
authored
feat: add support set/get object
1 parent 40b71fe commit 47804cf

File tree

2 files changed

+22
-6
lines changed

2 files changed

+22
-6
lines changed

README.md

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -155,18 +155,17 @@ storage.clearAll()
155155

156156
### Objects
157157

158-
```js
158+
```tsx
159159
const user = {
160160
username: 'Marc',
161161
age: 21
162162
}
163163

164-
// Serialize the object into a JSON string
165-
storage.set('user', JSON.stringify(user))
164+
// Set
165+
storage.setObject('user', user)
166166

167-
// Deserialize the JSON string into an object
168-
const jsonUser = storage.getString('user') // { 'username': 'Marc', 'age': 21 }
169-
const userObject = JSON.parse(jsonUser)
167+
// Get
168+
const userObject = storage.getObject<typeof user>('user') // {name: 'Marc', age: 21}
170169
```
171170

172171
### Encryption

src/MMKV.ts

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -185,6 +185,15 @@ export class MMKV implements MMKVInterface {
185185

186186
this.onValuesChanged([key]);
187187
}
188+
setObject(key: string, value: any): boolean {
189+
try {
190+
this.getFunctionFromCache('set')(key, JSON.stringify(value))
191+
this.onValuesChanged([key]);
192+
return true
193+
} catch {
194+
return false
195+
}
196+
}
188197
getBoolean(key: string): boolean | undefined {
189198
const func = this.getFunctionFromCache('getBoolean');
190199
return func(key);
@@ -193,6 +202,14 @@ export class MMKV implements MMKVInterface {
193202
const func = this.getFunctionFromCache('getString');
194203
return func(key);
195204
}
205+
getObject<T = any>(key: string): T | null {
206+
try {
207+
const valueString = this.getFunctionFromCache('getString')(key)
208+
return typeof valueString === 'string' ? JSON.parse(valueString) : null;
209+
} catch {
210+
return null
211+
}
212+
}
196213
getNumber(key: string): number | undefined {
197214
const func = this.getFunctionFromCache('getNumber');
198215
return func(key);

0 commit comments

Comments
 (0)