3

In my Stencil component, I want to initiate my state variable with the passed down prop value. How to do that in Stencil?

I have tried assigning the value to the state var in componentWillLoad, but it doesn't work.

@Prop() passedVal
@State() someVal = ??

I am new to Stencil, and I come from VueJS, so please bear with my seemingly noobish question.

Rutwick Gangurde
  • 4,772
  • 11
  • 53
  • 87

2 Answers2

4

It's best to watch the prop for changes, then update the state.

@Component({ tag: 'my-comp' })
export class MyComp {
  @Prop() foo: string;

  @State() bar: string;

  @Watch('foo')
  onFooChange() {
    this.bar = this.foo;
  }

  componentWillLoad() {
    this.onFooChange();
  }

  render() {
    return this.foo + this.bar;
  }
}

You can call your watcher method in componentWillLoad because watching will only start after the component has loaded.

Simon Hänisch
  • 4,740
  • 2
  • 30
  • 42
0

For future comers, @Watch takes the name of the @Prop variable to monitor as a parameter. Any time the value of that prop changes the function decorated by @Watch will be invoked with the newValue and oldValue as parameters.

export class SomeClass{
  @Prop() isValid: boolean = true;
  @Watch("isValid")
  watchHandler(newValue, oldValue) {
    console.log("newValue: ", newValue, "oldValue: ", oldValue);
    this.isValid = newValue;
  }
}
Alex
  • 1,982
  • 4
  • 37
  • 70