Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

stencil is not rerendeing component when @state() decorated property is changed

Tags:

stenciljs

I started with stencil today. Following code is all I have in my project. Docs say, if Component member decorated with @state() is changed, component will rerender.

Any changes to a @State() property will cause the components render function to be called again.

But even this simple thing is not working. Pls advice.

import {Component, State} from '@stencil/core';

@Component({
  tag: 'my-component',
  styleUrl: 'my-component.css',
  shadow: true
})
export class MyComponent {

  @State() name:string = 'john';

  changeName(){
    this.name = "Peter";
    console.log('inside changeName');
  }

  render() {
    return <div>
      <p>{this.name}</p>
      <button onClick={this.changeName}>click</button>
    </div>;
  }
}

When I click on the button inside changeName is logged but no changes to name is seen in view.

like image 795
asdasd Avatar asked Feb 24 '19 18:02

asdasd


2 Answers

Try changing your onClick to an arrow function:

<button onClick={() => this.changeName()}>click</button>

This preserves the meaning of this to reference your class. See https://stenciljs.com/docs/templating-jsx/#handling-user-input for more details and examples.

like image 111
matthewsteele Avatar answered Oct 01 '22 15:10

matthewsteele


@matthewsteele answer is right but you can also define your function like below to make it work.

private changeName = () => {
  this.name = "Peter";
  console.log('inside changeName');
}

Doing above the this reference will still preserves to the class.

like image 42
Sufiyan Ansari Avatar answered Oct 01 '22 13:10

Sufiyan Ansari