How to make an object reactive in LWC
By default all the properties are reactive in LWC, as in, once a property is created and used in a template file, when the content of the property is changed, the modified data gets reflected in all the places it is used (this behaviour is valid only when the property is used in the template file).
Let me take an example and explain what does @track
do.
There is an object person and this is the content of the object.
By default this property is not reactive when I try to change the content of the property (though it is used in the template file).
When I change the content of the object like this, the new value is not reflected in the template file.
That is because, the object is by default reactive when I try to change the complete content of the object like this.
Here am not just updating the value for one of the keys of the object, rather am assigning new definition to the object.
This is how the template file is going to be
If that is not what you need and if you want the object to be reactive even if one of the values for the key is changed, then we would need @track.
In the object above I have used @track decorator, because of this, when I make a small change to one of the keys of the object as shown below.
The object becomes reactive and the updated value gets displayed to the user on the template.
See Ya!