How to check if object is in Mobx observable array?
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
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.