Use Getters and Setters to Modify Data

To execute logic each time a public property is set, write a custom setter.

If you write a setter for a public property, you must also write a getter. Annotate either the getter or the setter with @api, but not both.

For consistency, the examples in this guide and in the lwc-recipes repo annotate the getter and present the getter before the setter.

To hold the property value inside the getter and setter, use a field. This example uses the _uppercaseItemName property, which is prefixed with an underscore to indicate that the property is private.

This sample <c-todo-item> component converts a string to uppercase.

The property value is provided to the template via the getter.

You can also handle errors in your getter with a try-catch block.

For another example of using a getter and setter, see the apiSetterGetter and todoList components in the lwc-recipes sample repo.

See Also