I am trying to implement computed getter function with argument like shown in this answer with MobX 6 and corresponding version of mobx-utils
.
export class CodificatorStore {
@observable.ref items: Array<Codificator> | null = null;
@action setItems(items: Array<Codificator>): void {
this.items = items;
}
@computed get item(): ITransformer<number, Codificator | null> {
return createTransformer((index: number): Codificator | null => {
console.log(`get item by index: ${index}`);
return this.items ? this.items[index] : null;
});
}
}
I expected created function to memoize the result of its execution each time I call it with the same argument and the same (not changed) observable items
but I get a new logged message on each call in render method of my React component:
codificatorStore.item(0);
According to docs and source code I expect that memoized value should be returned from reactiveView
on all consecutive calls instead of invoking my transform function. Do I misunderstand something? How can I achieve the desired result?
First of all, do you really need to memoize such simple operation? Or is it just an example?
Second, if you need just to memoize you don't need createTransformer
at all, it serves a bit different purpose. But you can use computedFn
, like that:
import { computedFn } from 'mobx-utils';
// ...
item = computedFn((index) => {
console.log(`get item by index: ${index}`);
return this.items ? this.items[index] : null;
});