waze waze -3 years ago 215
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) {
id: id,
nome: title,

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

@action removeEvento (id, title) {
var i = this.eventos.indexOf(id);
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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download