Issue
I am using Lit components library. In my code I fetch data and putting it in a reactive property. Then I am using repeat.js function from Lit to iterate thought that array. Everything is working but I got an error in console that I want to get rid of.
Here is fetch function:
async getData(){
try {
const response = await myFetch(`${baseURL}`, 'GET', '')
this.myProperty = response.data
} catch (err) {
if (err instanceof Error) {
console.log(err.message);
} else {
console.log('Unexpected error', err);
}
}
}
Here I declare my reactive property:
@property() myProperty: any
And here the iteration:
${repeat(this.myProperty, (item:any) => item.id, (item, index) => html`
<div>Data</div>
`)}
Solution
As @Lesiak pointed out in the comment, you need an initial value for the reactive property, otherwise it would be undefined
on first render and fail to iterate.
@property() myProperty: any[] = [];
For extra points of improvement, is myProperty
something you expect to be set from outside the component, or via an attribute? If so, it would be better to add the type option: (https://lit.dev/docs/components/properties/#conversion-type)
@property({type: Array}) myProperty: any[] = [];
If not, using @state()
decorator would be more relevant: (https://lit.dev/docs/components/properties/#internal-reactive-state)
@state() myProperty: any[] = [];
Answered By - Augustine Kim
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.