Open
Description
I think this interface change for useMMKVObject
is better; the developer can define if undefined is allowed or not.
export function useMMKVObject<T>(
key: string,
initialValue: T,
instance?: MMKV,
): [
value: T,
setValue: (
value: T | ((prevValue: T) => T | void)
) => void,
] {
const [json, setJson] = useMMKVString(key, instance);
const value = useMemo(() => {
if (json == null) return initialValue;
return JSON.parse(json) as T;
}, [json]);
const setValue = useCallback(
(v: (T) | ((prev: T) => T | void)) => {
if (v instanceof Function) {
setJson((currentJson) => {
const currentValue =
currentJson != null ? (JSON.parse(currentJson) as T) : initialValue;
const newValue = v(currentValue);
// Store the Object as a serialized Value or clear the value
return newValue != null ? JSON.stringify(newValue) : undefined;
});
} else {
// Store the Object as a serialized Value or clear the value
const newValue = v != null ? JSON.stringify(v) : undefined;
setJson(newValue);
}
},
[setJson]
);
return [value, setValue];
}
I haven't tested it yet but the changes are quite small to implement.
Metadata
Metadata
Assignees
Labels
No labels