0

I have a store with events

export class EventStore {

    @observable
    events: Event[] = [];

    @action
    addEvent(event: Event) {
        this.events = [...this.events, event]
    };
};

My Event look like this :

export class Event{
   
   classType: string;
}

I want to observe change on events properties of store BUT only of a specific classType

For Eg :

I have Event with classType "AddToCart" and "Order", and I want to observe only "Order" added, removed from events

I want to use import { observer } from "mobx-react"

Question :

Is there some magic trick to do in the EventStore or I have to handle it in my component (with some if) ?

My unperfect solution

Meanwhile, I'm doing somehting like this :

  reaction(
            () => eventStore.lastEvent,
            event => {
                if (event.classType === "Order")
                    this.newEvent = { ...event }
            }
  )
Xero
  • 3,951
  • 4
  • 41
  • 73

1 Answers1

1

You can add computed property

    @computed
    get orderEvents() {
        // Add whatever filtering you want
        return this.events.filter(event => event.classType === 'Order')
    };

If you need to pass arguments you could you computedFn from mobx-utils:

    filteredEvents = computedFn(function (classType) {
        return this.events.filter(event => event.classType === classType)
    })

Note: don't use arrow functions as the this would be incorrect.

https://github.com/mobxjs/mobx-utils#computedfn

https://mobx.js.org/refguide/computed-decorator.html#computeds-with-arguments

Danila
  • 15,606
  • 2
  • 35
  • 67
  • thanks for your answer. I upvote it, but this solution is not perfect for me, because I have to copy that for every classType – Xero Jul 16 '20 at 08:35
  • I've updated my answer with with `computedFn` where you can pass arguments. Is that better or still not what you need? – Danila Jul 16 '20 at 08:41