Use dynamic data in a GlimmerJS component

Bram Borggreve
InstructorBram Borggreve
Share this video with your friends

Social Share Links

Send Tweet
Published 7 years ago
Updated 5 years ago

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]
egghead
egghead
~ 17 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today