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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With