Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix persisting null with ObservablePersistMMKV #381

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

simontreny
Copy link

This PR fixes persisting null values in observable when using ObservablePersistMMKV.

Consider this piece of code:

const obs = observable<string | null>("foo");

syncObservable(obs, {
  persist: {
    name: "obs",
    plugin: ObservablePersistMMKV
  },
});

obs.set(null);

This logs the following error:

[Error: Second argument ('value') has to be of type bool, number or string!]

and the old value is restored on next launch.

This happens because the persist plugin tries to call storage.set(null) while it's not supported by react-native-mmkv

@simontreny simontreny force-pushed the fix-persisting-null-with-mmkv branch from aa28e7d to 32cba1a Compare October 31, 2024 13:35
@@ -85,7 +85,11 @@ export class ObservablePersistMMKV implements ObservablePersistPlugin {
const v = this.data[table];
if (v !== undefined) {
try {
storage.set(table, safeStringify(v));
if (v !== null) {
storage.set(table, safeStringify(v));
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

On second thought, I think the root issue is how safeStringify() is implemented:

return value ? JSON.stringify(value, replacer) : value;

It means that if the value is false (false, 0, "" or null), it won't be serialized as a string. If this called JSON.stringify() directly, this would work properly as null would be serialised "null" which can be saved and restored with MMKV.

I'm not sure I understand the intent of safeStringify(), I would expect it to always return either a string or undefined.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It probably also means that persisting 0 (or false) is broken too, as it will be persisted as a number but we will attempt to restore it with storage.getString()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant