Reputation: 26036
I am trying to pass a JSON string to my component prop and let the component parse the string into javascript object.
Unfortunately the @Watch decorator is not firing... what did I do wrong? I followed this documentation: https://stenciljs.com/docs/reactive-data#watch-decorator
Here are the relevant parts of my code:
ptw-input.tsx
import { Component, Prop, Watch } from "@stencil/core";
@Component({
tag: "ptw-input",
styleUrl: "ptw-input.css",
shadow: true
})
export class PtwInput {
@Prop() data: string;
innerData: any;
@Watch('data')
watchHandler(newValue: string): void {
this.innerData = JSON.parse(newValue);
console.log('this.innerData', this.innerData);
}
render(): JSX.Element {
return (
<input type="text"
placeholder={this.innerData.placeholder}
disabled={this.innerData.disabled}
maxlength={this.innerData.maxlength}
);
}
}
index.html
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=5.0">
<title>Stencil Component Starter</title>
<script src="/build/ptw.js"></script>
</head>
<body>
<ptw-input data='{"placeholder":"Type something", "disabled":false, "maxlength":4}'></ptw-input>
</body>
</html>
... and here is my package.json
{
"name": "ptw-input",
"version": "0.0.1",
"description": "PTW input component",
"module": "dist/esm/index.js",
"main": "dist/index.js",
"types": "dist/types/components.d.ts",
"collection": "dist/collection/collection-manifest.json",
"files": [
"dist/"
],
"scripts": {
"build": "stencil build",
"dev": "sd concurrent \"stencil build --dev --watch\" \"stencil-dev-server\" ",
"serve": "stencil-dev-server",
"start": "npm run dev",
"test": "jest",
"test.watch": "jest --watch"
},
"dependencies": {},
"devDependencies": {
"@stencil/core": "^0.9.11",
"@stencil/dev-server": "latest",
"@stencil/utils": "latest",
"@types/jest": "^21.1.1",
"jest": "^21.2.1"
},
"repository": {
"type": "git",
"url": "git+https://github.com/ionic-team/stencil-component-starter.git"
},
"author": "Ionic Team",
"license": "MIT",
"bugs": {
"url": "https://github.com/ionic-team/stencil"
},
"homepage": "https://github.com/ionic-team/stencil",
"jest": {
"transform": {
"^.+\\.(ts|tsx)$": "<rootDir>/node_modules/@stencil/core/testing/jest.preprocessor.js"
},
"testRegex": "(/__tests__/.*|\\.(test|spec))\\.(tsx?|jsx?)$",
"moduleFileExtensions": [
"ts",
"tsx",
"js",
"json",
"jsx"
]
}
}
I am using the latest stenciljs as shown in the package.json, but there is nothing in the console log except this error: TypeError: Cannot read property 'placeholder' of undefined
Upvotes: 2
Views: 5423
Reputation: 1872
The @Watch
decorator does not fire when a component initially loads.
To get the method to run when the component loads, invoke it inside a componentWillLoad
lifecycle hook:
componentWillLoad() {
this.watchHandler(this.newValue);
}
Upvotes: 11