diff --git a/README.md b/README.md index 8652bbbe..732ee8eb 100644 --- a/README.md +++ b/README.md @@ -155,18 +155,17 @@ storage.clearAll() ### Objects -```js +```tsx const user = { username: 'Marc', age: 21 } -// Serialize the object into a JSON string -storage.set('user', JSON.stringify(user)) +// Set +storage.setObject('user', user) -// Deserialize the JSON string into an object -const jsonUser = storage.getString('user') // { 'username': 'Marc', 'age': 21 } -const userObject = JSON.parse(jsonUser) +// Get +const userObject = storage.getObject<typeof user>('user') // {name: 'Marc', age: 21} ``` ### Encryption diff --git a/example/.eslintrc.js b/example/.eslintrc.js new file mode 100644 index 00000000..8673c6c3 --- /dev/null +++ b/example/.eslintrc.js @@ -0,0 +1,11 @@ +module.exports = { + parser: '@typescript-eslint/parser', + plugins: [], + parserOptions: { + sourceType: 'module', + }, + env: { + node: true, + es2020: true, + }, +}; diff --git a/src/MMKV.ts b/src/MMKV.ts index 973a5e74..50f3397f 100644 --- a/src/MMKV.ts +++ b/src/MMKV.ts @@ -185,6 +185,15 @@ export class MMKV implements MMKVInterface { this.onValuesChanged([key]); } + setObject(key: string, value: any): boolean { + try { + this.getFunctionFromCache('set')(key, JSON.stringify(value)); + this.onValuesChanged([key]); + return true; + } catch { + return false; + } + } getBoolean(key: string): boolean | undefined { const func = this.getFunctionFromCache('getBoolean'); return func(key); @@ -193,6 +202,14 @@ export class MMKV implements MMKVInterface { const func = this.getFunctionFromCache('getString'); return func(key); } + getObject<T = any>(key: string): T | null { + try { + const valueString = this.getFunctionFromCache('getString')(key); + return typeof valueString === 'string' ? JSON.parse(valueString) : null; + } catch { + return null; + } + } getNumber(key: string): number | undefined { const func = this.getFunctionFromCache('getNumber'); return func(key); diff --git a/src/createMMKV.web.ts b/src/createMMKV.web.ts index 88503a21..4a312e7e 100644 --- a/src/createMMKV.web.ts +++ b/src/createMMKV.web.ts @@ -26,7 +26,7 @@ export const createMMKV = (config: MMKVConfiguration): NativeMMKV => { if (config.path != null) { throw new Error("MMKV: 'path' is not supported on Web!"); } - + // canUseDOM check prevents spam in Node server environments, such as Next.js server side props. if (!hasAccessToLocalStorage() && canUseDOM) { console.warn(