-1

I have a input data in component:

@Input() sogllist: any[] = [];

Why is the mutation approach like the one here not recommended?

public remove(e: any, sogl: any): void {
    this.sogllist = this.sogllist.filter((sgl) => sgl.id !== sogl.id);
}

How to do that correctly?

PMO1948
  • 2,210
  • 11
  • 34
  • reading stuff: https://medium.com/@jamesjefferyuk/javascript-what-are-pure-functions-4d4d5392d49c –  Dec 29 '20 at 14:35
  • I did not get, it illustrates a different example –  Dec 29 '20 at 14:44
  • 2
    The mutation is a bad programming practice. If your code is mutable, you might change or break something without knowing. The code becomes harder to read and test, produces non-predictable side effects. Therefore you better need so-called pure functions. https://blog.bitsrc.io/understanding-javascript-mutation-and-pure-functions-7231cc2180d3 –  Dec 29 '20 at 15:11
  • 1
    Pros. / Cons. of Immutability vs. Mutability: https://stackoverflow.com/questions/1863515/pros-cons-of-immutability-vs-mutability – ChristianB Dec 29 '20 at 19:22

1 Answers1

0

Your input should remain unchanged so as to not confuse the flow of things. If you need it to be filtered, try doing something like this:

@Input() sogllist: any[] = [];
filteredList: any[];

public remove(e: any, sogl: any): void {
    this.filteredList= this.sogllist.filter((sgl) => sgl.id !== sogl.id);
}

You should also give filteredList the original value of sogllist (either in a setter or in ngOnInit) and then replace your usages of sogllist with filteredList

PMO1948
  • 2,210
  • 11
  • 34