waze waze - 10 months ago 101
Javascript Question

React-Native Mobx remove item

How can I remove an item from an array in Mobx observable?

This is the observable:

@persist('list') @observable eventos = []


This is how I add an item to the list:

@action addEvento (id, title) {
this.eventos.push({
id: id,
nome: title,
})
}


and this is what I've tried to remove it:

@action removeEvento (id, title) {
var i = this.eventos.indexOf(id);
console.log(i)
if(i != -1) {
this.eventos.splice(i, 1)
return this.eventos
}
}


But it always removes the last item added, instead of the item that I want to remove. Also, indexOf always returns -1.

Answer Source

You are trying to find the index of the element with value id, but you want to find where the object's id is equal to id.

You could e.g. use a filter and replace instead:

@action removeEvento (id, title) {
  var filteredEventos = this.eventos.filter(evento => evento.id !== id);
  this.eventos.replace(filteredEventos);
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download