quarrant / mobx-persist-store

Persist and rehydrate observable properties in mobx store.
268 stars 14 forks source link

Writing outside Mobx scope do not rehydrate values from storage #23

Closed frangeris closed 3 years ago

frangeris commented 3 years ago

Thanks for the lib, currently the only persistence that have support for Mobx 6.

I have a scenario where I need to write to local storage outside of the store due I don't have access via classes, this scenario is "receiving push notifications in background":

// background handler (push notification)
messaging().setBackgroundMessageHandler(async (remote) => {
  let notifications = await AsyncStorage.getItem("Notification");
  notifications = JSON.parse(notifications || "{}");
  notifications?.data?.push(remote.data);
  await AsyncStorage.setItem("Notification", JSON.stringify(notifications));
});

Then inside the view that I list my notifications:

const Notifications = ({ navigation, ...props }) => {
  const { notifications } = useStore();
  useEffect(() => {
    notifications.sync();
  }, []);

The store:

import { makeAutoObservable, observable, action } from "mobx";
import { rehydrate } from "mobx-persist-store";

export default class {
  @observable data: any[] = [];

  constructor() {
    makeAutoObservable(this);
  }

  @action
  sync() {
    rehydrate(this);
  }
}

And creating the instance

    this.notifications = persistence({
      name: "Notification",
      properties: ["data"],
      adapter: new StorageAdapter({
        read,
        write,
      }),
    })(new Notifications());

Other way works fine (normal), the issue is that is not syncing outside of react even if I call the rehydrate method when entering the view.

If I reload the app (shake) I can see the data written and listed

What am I missing?

Thanks..

quarrant commented 3 years ago

Thank you, @frangeris!

The rehydrate only waiting when finished synchronization with storage and not start anything.

I think you needed real force sync function, but the library doesn't have it

And why you couldn't push data to store?

frangeris commented 3 years ago

@quarrant sorry for delay to answer,

Answering your question, I can push to the store, I tried, but the data is not reflected, the issue why cant push directly is due that I dont react context handleling push notifications in background, that's the reason why I wrote to the local storage directly instead, so when the user opens again the app, so can see the notifications saved when the app was in background, if not, I would lose those payloads... thats why I need to force a "re-sync" to get those payloads saves on background

codeBelt commented 3 years ago

@frangeris

Let me know if how this new version works for you