Join egghead, unlock knowledge.

Want more egghead? It's 45% off for a limited time only!

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock All Content for 45% Off

Already subscribed? Sign In

Save 45% for a limited time.

Get access to all courses and lessons on egghead today.

Autoplay

    Use dynamic data in a GlimmerJS component

    Bram BorggreveBram Borggreve

    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]
    emberEmber.js
    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Discuss

    Discuss