Computed method with parameters in mobx

Viewed 1735

Suppose I have an object ResourceX that looks like this.

interface ResourceX {
  id: string,
  type: string,
  label: string
}

I also have a backend API, that allows me to fetch a ResourceX with a certain id (resourceService.get(123) = Resource with id 123)

Now on the frontend I would like to store and access a certain ResourceX in an observable map of a mobx store. And when retrieving the ResourceX from my store I want to make sure that possible observers of a certain ResourceX only react to changes in the resource object itself and not the whole observable map - therefore I use computed in the get(id) method.

The store looks something like this:

class ResourceStore {
    @observable resources: Map<string, ResourceX> = new Map();

    /**
     * Loads the ResourceX with the given id from the server
     * and stores it in the observable map.
     */
    @action loadResourceX(id: string) {
        return resourceService.get(id).then(resource => {
            this.resources.set(id, resource))
    }

    /**
     * Gets the ResourceX with the given id from the store.
     */
    public getResourceX(id: string) {
        return computed(() => this.resources.get(id)).get();
    }
}

Since @computed can only be used on getters they cannot take any parameters. Therefore I have to use the computed(() => ...) syntax.

Now my question is if there is any specific reason that mobx out of the box only provides @computed for getters without parameters and maybe there is a more "mobx" way to do what I am trying to do?

I am aware of https://github.com/mobxjs/mobx/issues/291 but I'd like to know if I am maybe using mobx in a wrong way.

0 Answers
Related