ammarahm-ed / react-native-mmkv-storage

An ultra fast (0.0002s read/write), small & encrypted mobile key-value storage framework for React Native written in C++ using JSI
https://rnmmkv.now.sh
MIT License
1.59k stars 111 forks source link

[Bug/Missing Feature] object/map storage doesn't provide reviver function #277

Open douugdev opened 2 years ago

douugdev commented 2 years ago

Description of the issue Passing an object with date to useMMKVStorage will return the string representation of the date on subsequent renders:

// inside component
const [value, setValue] = useMMKVStorage<{date: Date}>(storage, { date: new Date() });

// first renders while value isn't retrieved from cold storage
console.log(typeof value); // object

// after restarting the app
console.log(typeof value); // string 

Example of parsing without reviver: https://github.com/ammarahm-ed/react-native-mmkv-storage/blob/01edd658b9ead6c18fbc8bb82af2c573007d9d8e/src/indexer/maps.ts#L44

Expected behavior object/map storage should have a reviver function parameter which is then passed to JSON.parse

PS.: I can probably fix it, just creating this issue confirming this is not working as intended

ammarahm-ed commented 2 years ago

The useMMKVStorage hook works in isolation from the main storage library. Hence if we do use a reviver function it would be at initialization. Or another option is to pass it into the hook but use it to fix already parsed object. In your case it's the date. Something like this:

const [value, setValue] = useMMKVStorage<{date: Date}>(storage, { date: new Date() }, {
parse: (value) => {
value.date = new Date(value.date);
return value;
}
});

A PR would be great.