Mobx: No way to reaction on filtered list

Created on 20 Sep 2020  ยท  4Comments  ยท  Source: mobxjs/mobx

I want to listen to the change on specific items of list. I used reaction on my list and I filtered my list to get the specific items which I need to listen, but reaction fires when new new item adds to list (out of my filtered list)

This is my code:

const MyCustomModel = types
  .model({
    id: types.identifier,
    start: types.Date,
    end: types.Date,
  });

const MyStore = types
  .model({
    id: types.identifier,
    items: types.map(MyCustomModel),
  })
  .views(self => ({
    get itemsArray() {
      return Array.from(self.items.values());
    },
  }))
  .actions(self => {
    return {
      setListener(start: Date, end: Date) {
        myReactionDisposer = reaction(
          () =>
            self.itemsArray
              .filter(
                item =>
                  item.end.getTime() >= self.start.getTime() &&
                  item.start.getTime() <= self.end.getTime(),
              )
              .map(item=> item),
          () => {
            console.log('my reaction fires!');
            // other codes
          },
        );
      },
  });

For example if I listen to the range 2020-09-20 00:00:00 to 2020-09-21 00:00:00
and I add new item with a start and end value in another day {start: '2020-09-15 10:00:00' , end: '2020-09-15 16:20:00'} , the reaction fires!

โ” question

All 4 comments

Using autorun instead of reaction should help I think. If not, please convert this to CodeSandbox to see it in action.

That's because you always return different value (new array) from data function.
Try reaction(data,effect, { equals: comparer.structural }) or provide custom equals function.

Thanks @urugator
It works for me with { equals: comparer.shallow}
I couldn't find any document that describes each of these comparer functions! Is there any documents on this?

@SiSa68 https://deploy-preview-2327--mobx-docs.netlify.app/refguide/computed.html#-built-in-comparers

Note it's a new doc for the upcoming MobX 6, but it's structured much better and these basic things haven't really changed.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

bakedog417 picture bakedog417  ยท  3Comments

kirhim picture kirhim  ยท  3Comments

kmalakoff picture kmalakoff  ยท  4Comments

bb picture bb  ยท  3Comments

mehdi-cit picture mehdi-cit  ยท  3Comments