quarrant / mobx-persist-store

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

[Feature] Prevent `hydrateStore` call when `makePersistable` is called #82

Open codeBelt opened 2 years ago

codeBelt commented 2 years ago

I think there might be situation where you don't want the observable to hydrate right away when makePersistable is called.

For example in my application the user can send another user a url with query params so the page will be configured from the query params and not the persisted data.

We could determine if there is query params and wrap makePersistable in a if statement like this:

export class EmployeesPageStore {
  // ...
  constructor() {
    makeAutoObservable(this, {}, { autoBind: true });

    if (hasNoQueryParams) {
      makePersistable(this, {
        name: 'EmployeePageStore',
        properties: ['currentBillingOption', 'currentFilterStatus', 'currentSelectedEmployeeType'],
      });
    }
  }

  async init() {
    await this.loadAllEmployees();
  }
}

But what if we had more control over when the observable gets hydrated. What if we allowed a property (preventInitialHydration) to be set so makePersistable does not automatically hydrate the observable. Then we can call hydrateStore later on if needed.

export class EmployeesPageStore {
  // ...
  constructor() {
    makeAutoObservable(this, {}, { autoBind: true });

    makePersistable(this, {
      name: 'EmployeePageStore',
      preventInitialHydration: true,
      properties: ['currentBillingOption', 'currentFilterStatus', 'currentSelectedEmployeeType'],
    });
  }

  async init() {
    if (hasNoQueryParams) {
      await hydrateStore(this);
    }

    await this.loadAllEmployees();
  }
}
  1. What do you think?
  2. Is there a better name than preventInitialHydration?
quarrant commented 2 years ago

I didn’t think about this case before, but in your example it seems like a good idea)

Honestly, preventInitialHydration looks like something hard for understanding (maybe I mistake here) and I offer you other name - autoHidrate

codeBelt commented 2 years ago

I like the name autoHydrate. I will probably work on a PR this weekend and you can see what I come up with. First I think I am going to write more tests so I don't mess things up.

codeBelt commented 2 years ago

I am going to work on this still but it will be a few weeks now until I can.

yixiaojiu commented 1 year ago

Has this problem been solved?