Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to implement Computed and Watchers functionality in lit #1193

Open
rajeevnttdata opened this issue Sep 22, 2023 · 1 comment
Open

How to implement Computed and Watchers functionality in lit #1193

rajeevnttdata opened this issue Sep 22, 2023 · 1 comment

Comments

@rajeevnttdata
Copy link

rajeevnttdata commented Sep 22, 2023

Hello Team,

I just wanted to know how to achieve computed and watch functionality in the lit element.
Computed:- A computed property automatically tracks its reactive dependencies.
computed: {
// a computed getter
reversedMessage: function () {
// this points to the vm instance
return this.message.split('').reverse().join('')
}
}

Watchers:- Computed properties allow us to declaratively compute derived values. However, there are cases where we need to perform "side effects" in reaction to state changes - for example, mutating the DOM, or changing another piece of state based on the result of an async operation.

With Composition API, we can use them to trigger a callback whenever a piece of reactive state changes

const obj = reactive({ count: 0 })

watch(obj, (newValue, oldValue) => {
// fires on nested property mutations
// Note: newValue will be equal to oldValue here
// because they both point to the same object!
})

obj.count++

Developers if we can implement functionality Computed and Watchers. Just let me know ?

@justinfagnani
Copy link
Contributor

Maybe we can clarify in docs, but there's generally no need for a computed value primitive in Lit, since you can just use JavaScript to compute new values during a render.

You can use either a local variable:

  @property() message: string = '';
  
  render() {
    const reversedMessage = this.message.split('').reverse().join('');
    return html`reversedMessage = ${reversedMessage}`;
  }

or a getter:

  @property() message: string = '';

  private get reversedMessage() {
    return this.message.split('').reverse().join('');
  }
  
  render() {
    return html`reversedMessage = ${this.reversedMessage}`;
  }

As for watchers, you can see what values changed in the lifecycle hooks willUpdate() and updated():

  @property() message: string = '';
  
  willUpdate(changedProperties) {
    if (changedProperties.has('message')) {
      // do something
    }
  }

See https://lit.dev/docs/components/lifecycle/#willupdate

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
Status: No status
Development

No branches or pull requests

2 participants