Stencil JS - Initiate a State variable with a Prop value?

Viewed 850

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.

2 Answers

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.

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;
  }
}
Related