4

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.

Skilla123
  • 81
  • 1
  • 1
  • 7
  • You are missing some concepts here. A getter in JS land is _a function that returns the value of some property on some object_. The syntax looks like `get answer() { return 42; }`. A `get` method on a class/object is just that -- a method named `get`, not a _real_ getter This is the reason why you can't have parameterised getters anywhere in JS, not even MobX. – gustavohenke Dec 20 '18 at 06:53
  • Thank you for clarifying! I should have worded my final question a bit differently. I am not referring to JS getters but methods of the class in general. What is the reason that mobx out of the box only provides the decorator syntax for JS getters and not for normal methods (as described in my method above). I edited my post to better reflect the essence of my question, thanks again! – Skilla123 Dec 21 '18 at 19:54

0 Answers0