Use dynamic data in a GlimmerJS component

InstructorBram Borggreve

Share this video with your friends

Send Tweet

In this lesson we will create an updateContent method that sets the value of our content property to the current epoch timestamp. We need to call toString() on the Date.now() method in order to make TypeScript happy.

updateContent() {
  this.content = Date.now().toString()
}

We create a constructor that takes the options parameter, call super(options) and call into our this.updateContent() method.

constructor(options) {
  super(options)
  this.updateContent()
}

When we refresh our page we can see that the value of content is set to the epoch timestamp.

To make the content really dynamic we use setInterval() to call into updateContent each second: setInterval(() => this.updateContent(), 1000).

When we save our file we see that our content does not get updated anymore and when we check the console we see that we get an error telling us that: The 'content' property on the my-component component was changed after it had been rendered. The error also informs us that we should Use the @tracked decorator to mark this as a tracked property.

We add the @tracked decorator to our property, we import tracked from @glimmer/component and we refresh the page. We verify that content gets updated each second.

We change our updateContent to add our the timestamp to the array. When we use this.items.push(this.content) to achieve this we see that the list does not get updated. This is because the @tracked decorator only tracks the re-assignment of properties.

The way to get this working is by re-assigning our items array inside updateContent. We assign a new array, de-structure the current items array and add the new content.

this.items = [...this.items, this.content]