react-native-mmkv icon indicating copy to clipboard operation
react-native-mmkv copied to clipboard

feat: add support set/get object

Open ngocle2497 opened this issue 1 year ago • 7 comments

Add support set/get object, array, ...

ngocle2497 avatar Jul 18 '23 09:07 ngocle2497

Hey thanks for your PR!

I don't think this is a good thing to add to the library, I would prefer the JSON.stringify/JSON.parse stuff to stay in user code because this is making type assumptions that simply aren't true and aren't typechecked. I'll think about it.

mrousavy avatar Jul 18 '23 09:07 mrousavy

@mrousavy , actually when use this library, I alway create a common function to save/get object each project. i think it will help someone like me

ngocle2497 avatar Jul 18 '23 09:07 ngocle2497

I would also love to have an get/set equivalent to the useMMKVObject method, which in fact also uses JSON.parse and JSON.stringify under the hood (https://github.com/mrousavy/react-native-mmkv/blob/40b71fe27269ee4c0bd5bfb83ee626bf41535cba/src/hooks.ts#L178-L202).

Currently when I use the hook and also need some direct getter for an object/array, then I need to write a helper method. Types are not checked by my helper function either, but this is okay.

By the way, thank for this package, I migrated all projects from AsyncStorage to MMKV 👍 And I will use it with or without "get/setObject" 😉

fabianbru avatar Aug 01 '23 19:08 fabianbru

@mrousavy well, recently I noticed that I don't have to JSON.stringify(object) when using set function to persist an object. I'm using 2.11.0, because when I use getString(key) and then JSON.parse it, I have to JSON.parse twice to get the original object I persisted. I read the souce code and find nothing.

is there anything I'm missing?

chj-damon avatar Dec 05 '23 02:12 chj-damon

even the object I want to persist is an Object Array, I also don't need to JSON.stringify it. which confuses me since you said developers have to handle the parse/stringify themselves.

chj-damon avatar Dec 05 '23 02:12 chj-damon

sorry about my comments, I'm using react-native-mmkv with atomWithStorage in jotai, setItem in createJSONStorage already stringify the value so I don't have to. which makes everything sense.

chj-damon avatar Dec 05 '23 02:12 chj-damon

@mrousavy , actually when use this library, I alway create a common function to save/get object each project. i think it will help someone like me

Yea I know, but this is probably a good thing. If I add setObject and getObject functions, the user might assume that those objects are safely typed - which they are absolutely not. Your storage could get corrupted, someone else (notification extension? previous version of your app? etc) could write to that key, and your object might look entirely different from what the type suggests.

mrousavy avatar Jan 18 '24 15:01 mrousavy