mobx-persist-store icon indicating copy to clipboard operation
mobx-persist-store copied to clipboard

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

Open codeBelt opened this issue 2 years ago • 4 comments

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?

codeBelt avatar Jun 02 '22 21:06 codeBelt