Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 559
waze Avatar asked Jan 18 '26 10:01

waze


1 Answers

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);
}
like image 152
Tholle Avatar answered Jan 21 '26 09:01

Tholle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!