Categories
Angular Java Script Tutorials

Component Immutability and RequiredArray

While reading through component design, one of the recommended tip is to never mutate the input properties.

Let’s look at the example below. (I am using Angular but same can apply to other frameworks)

    @Component({...})
class MyComponent {
    @Input() status: Status[];
    get sortedStatus() {
        return this.status.sort();
    }
}

Here sort is a mutable operation. This not only sort the array but also mutates the array.

I have prepared the stackblitz. Here we have status array of type string. It’s passed down to child component. It’s displayed both in parent and child component. In the child component I have a button Sort Array that basically sorts the status that is received via @Input().

Sort Array from child component sort array and it is reflected in parent component

We can prevent this behavior by using the ReadonlyArray

This interface strips away all the mutable operations like push, pop, shift, unshift along with sort.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.