Immutability in the angular components

Asked

Viewed 33 times

2

Hello, I am learning functional programming and would like to know how to apply the principle of immutability in the angular components. For example, in the case below I have a list of files that the user selects and displays on the screen, for this I usually create a variable outside the function that will receive these files and list them with *ngFor in a list, this kind of thing hurts the principle of immutability and makes my function unclean, it is not?

    files: FileList

  constructor() { }

  innerWidth: number;
  ngOnInit(): void {
  }

  receivedFiles(files: FileList){
    this.files = files;
  }

1 answer

2


This is a complex question that would be better explained in a lecture than in a stackoverflow answer. The first thing you have to notice is that components are classes and in your case these files are a property of this class and not a variable.

The second important point is to understand the difference between mutation and reassigment, for this see the case when using const

const obj ={prop: 'abc'}

obj.prop ='cde' // mutação e funciona com consts 

obj={prop: 'cde'}  // reassigments e não funciona com consts

At angular one should always use reassigments instead of mutation in the properties of the components because the angular detects this reassigment and uses cdr to upgrade, although also upgrade to mutation it does not work for Pure components an ex pro your case

this.files=files // detectado para pure componentes

this.files[0]='exemplo' // não detectado para pure componentes
this.files.prop = 'exemplo' // não detectado para pure componentes

In your case this.files= is the best thing to do is not a mutation.

A common case of that is that one should always make an assigment of a result of an observable and not a mutation

Another tip to avoid mutation is to use array functions (map,filer,reduce) instead of for

Tip 3 is to use primitive types whenever possible because they always create a new reference when changing the value

If you really wanted to force yourself to be mutation-free you can use Object.Freeze

The subject is complex and has more scenarios but I hope it was clear.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.