Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if object is in Mobx observable array?

I'm using indexOf in a React component to style a button based on whether an object is in an mobx observable array.

The button is for favoriting. It pushes the object for that specific list item into an observable array in the store called 'favorites'. favorites is an observable array of objects.

Here's the ES6 template literal from my button:

className={`btn-group ${((this.props.store.favorites.indexOf(this.props.data) > -1)) ? 'success' : 'info'}`}

Basically, it's a check for if the object is in the array, className will be success, if false info.

This works perfectly fine when the favorites array is in local state. But I get that the objects within the favorites array look differently once they are in the observable array. I get that the observable array favorites is different than a local array favorites.

But how do I do a test for whether an object is in an observable array of objects? I tried slice() and peek() and using the findIndex but no dice.

like image 601
Kyle Pennell Avatar asked Apr 19 '17 03:04

Kyle Pennell


2 Answers

Regarding the doc: isObservableArray

Returns true if the given object is an array that was made observable using mobx.observable(array).

So to know if data is in an observable favorites array:

// If data is a primitive
className={`btn-group ${mobx.isObservableArray(this.props.store.favorites) && this.props.store.favorites.indexOf(this.props.data) > -1 ? 'success' : 'info'}`}

// Id data is an object it is a little more verbose and coupled to your data
// structure. You have to use the `find` function to iterate and test if an 
// element in the array has the same id.
className={`btn-group ${mobx.isObservableArray(this.props.store.favorites) && !!this.props.store.favorites.find(fav => fav.id === this.props.data.id) ? 'success' : 'info'}`}

Here is a POC with a function helper: https://jsbin.com/botijom/edit?js,console

like image 185
dagatsoin Avatar answered Sep 28 '22 19:09

dagatsoin


Michel (mobx creator) gave me the hint I needed via the Gitter channel.

I actually needed a shallowly observable array, not a deeply observable one. I don't need each and every property of the objects in the array to be observable (hence all the sets/gets on the object properties I was seeing before), just whether an object is added or removed.

So I changed it from

@observable favorites = []

to

 @observable favorites = observable.shallowArray();

Ultimately, though @dagatsoin 's answer is right if you need to use a deeply observable array.

like image 39
Kyle Pennell Avatar answered Sep 28 '22 18:09

Kyle Pennell