Use Binded data on the logic part on LIT

Viewed 38

I have been looking for information about variable binning. The problem is that I don't want to use those variables inside my HTML render, but in the component logic (i want to fetch some data). How do I declare it?

  constructor(){
    super();
    this.url = "https://....";
  }


  render() {
    return html`
       <parent-component .url ="${this.url}"></parent-component>
    `;

child component:

  constructor() {
    super();
    fetch(this.url)
    .then(response => response.json())
    .then(data =>{this.ArrayData = data.results
      this.requestUpdate()
    })
  }

Thank you very much

1 Answers

To bind data, declare a reactive property for properties that can trigger the reactive update cycle when changed, re-rendering the component.

From your example I'm not exactly sure when you want to trigger the fetch in the child component. I'll assume you want to fetch the data once with this.url passed from the parent as a property binding.

The issue I see in the code sample is that this.url will be undefined in the constructor of the child component, as the outer element needs to render and set the property .url on the child. Moving the logic in the constructor to the firstUpdated lifecycle callback should fix the issue, as this.url will now be defined.

An additional change I included in the code sample, is making this.ArrayData a reactive property, allowing the removal of this.requestUpdate.

Minimal example of fix in the Lit Playground.

Related