Skip to content

Code Update - useMMKVObject doesn't force undefined. #799

Open
@christo8989

Description

@christo8989

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

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions