quarrant / mobx-persist-store

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

[Feature] Support asynchronous StorageController functions #91

Closed nathan-alden-sr closed 2 years ago

nathan-alden-sr commented 2 years ago

I created a simple object that conforms to StorageController:

import localForage from "localforage";
import { StorageController } from "mobx-persist-store";

const localForageEntityStorageController: StorageController = {
  // eslint-disable-next-line @typescript-eslint/promise-function-async
  getItem: <U>(key: string) => {
    return localForage.getItem<U>(key);
  },

  // eslint-disable-next-line @typescript-eslint/promise-function-async
  removeItem: (key: string) => {
    return localForage.removeItem(key);
  },

  // eslint-disable-next-line @typescript-eslint/promise-function-async
  setItem: (key: string, value: any) => {
    return localForage.setItem(key, value);
  }
};

export default localForageEntityStorageController;

Then I provide this object to mobx-persist-store during initial configuration:

import { makeAutoObservable } from "mobx";
import { makePersistable } from "mobx-persist-store";
import Todo from "../entities/Todo";
import localForageEntityStorageController from "./LocalForageEntityStorageController";

class TodoStore {
  public todos: Todo[] = [];

  public constructor() {
    makeAutoObservable(this);

    makePersistable(
      this,
      {
        name: "Todos",
        properties: ["todos"],
        storage: localForageEntityStorageController,
        stringify: true
      },
      {
        delay: 200
      }
    );
  }
}

export default new TodoStore();

You can see how I have to disable the @typescript-eslint/promise-function-async lint rule. This is because mobx-persist-store will error if I pass anonymous functions for my StorageController methods. This is inconvenient as it forces me to use the legacy then syntax with promises.

The following internal function (and perhaps callers) could be modified to support asynchronous functions:

https://github.com/quarrant/mobx-persist-store/blob/25bab48a8c8ef11dff0466d3f1e3295c0e8e9acc/src/utils.ts#L31-L33

[object AsyncFunction] is what is reported (at least in Firefox) when I pass anonymous functions.