Skip to content

Commit

Permalink
etValue prevValue support for useMMKVObject hooks
Browse files Browse the repository at this point in the history
  • Loading branch information
fahad86 committed Jan 18, 2024
1 parent 6fa83b5 commit c5c4d24
Showing 1 changed file with 15 additions and 14 deletions.
29 changes: 15 additions & 14 deletions src/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -177,24 +177,25 @@ export function useMMKVObject<T>(
key: string,
instance?: MMKV
): [value: T | undefined, setValue: (value: T | undefined) => void] {
const [string, setString] = useMMKVString(key, instance);
const [json, setJson] = useMMKVString(key, instance);

const value = useMemo(() => (json ? JSON.parse(json) : undefined), [json]);

const value = useMemo(() => {
if (string == null) return undefined;
return JSON.parse(string) as T;
}, [string]);
const setValue = useCallback(
(v: T | undefined) => {
if (v == null) {
// Clear the Value
setString(undefined);
(v: (T | undefined) | ((prev: T | undefined) => T | undefined)) => {
if (v instanceof Function) {
setJson((currentJson) => {
const newValue = v(
currentJson ? JSON.parse(currentJson) : undefined,
);
return JSON.stringify(newValue);
});
} else {
// Store the Object as a serialized Value
setString(JSON.stringify(v));
// Store the Object as a serialized Value or clear the value
setJson(v ? JSON.stringify(v) : undefined);
}
},
[setString]
);
},
[setJson]);

return [value, setValue];
}
Expand Down

0 comments on commit c5c4d24

Please sign in to comment.