Support for getJson / getObject in MMKV
I would suggest to add a function getJson / getObject, which automatically JSON.parse the underlying string from the storage. useMMKVObject already exists for this, but I would love to have the same functionality, when using the storage directly.
The same extension of course for the set method.
Guten Tag, Hans here! 🍻 Thanks for your suggestion about adding getJson or getObject in MMKV. It's great to see you're interested in improving ze library!
Currently, useMMKVObject does provide this functionality, but I understand wanting similar direct access methods. Please consider making a feature request in ze dedicated area for new features, where mrousavy and others can discuss its implementation.
Also, if you find ze project helpful, sponsoring mrousavy could really support further development: Become a sponsor.
Thanks for your input!
Note: If you think I made a mistake, please ping
@mrousavyto take a look.
@mrousavy I can't find a dedicated area for new features.
I don't think this is a good idea because JSON.parse is never checking for type-safety. It's always theoretically unknown.
Is there a difference to the useMMKVObject hook? I don't really understand why the hook exists, but no method in the mmkv. I think it would be handy to have it also there. Now I always have to manually check for undefined und JSON.parse it then.
I think type-safety is a developer error. I would add generics with default to any.
No this is essentially just a convenience hook, but I agree since I introduced this hook it maybe makes sense to also add it to JS types of MMKV.
@mrousavy I think I could implement this, if you don't mind. Here are the changes we could make:
- Modify the
setmethod to detect whether the passed value is a serializable object (i.e., can be safely stringified into JSON) and not an ArrayBuffer; then stringify the object to store it as a string, similar to how theuseMMKVObjecthook works. - Introduce a new
getObjectmethod that parses the stored object from JSON. - Incorporate the changes from https://github.com/mrousavy/react-native-mmkv/pull/826, so that storable objects support the correct types.
Thoughts?
- Incorporate the changes from https://github.com/mrousavy/react-native-mmkv/pull/826, so that storable objects support the correct types. Thoughts?
That shouldn't be part of MMKV imo.
The rest sounds good - but maybe it would be even better to use binary serialization once that lands in a public Hermes release: https://x.com/mrousavy/status/1996152362906382477?s=20