Web-Components/Elements-with-JS

I am using the Github/Time-Elements (https://github.com/github/time-elements) package, which allows you to print out your datetime in utc and then simply have that converted to the local time and formatting according to the browser’s location.

Example:

<local-time datetime="2014-04-01T16:30:00-08:00">
  April 1, 2014 4:30pm
</local-time>

However… when I use this element within a Livewire component that is polling then the timezone conversion stops working after the initial render. This got me thinking that other people have problems with elements requiring JS evocation on render?

If you are using a such an element within a polling Livewire component, how did you solve this?

Thank you.

If you’re intending to use this package, you might need it to run every time you poll so that it’ll refresh the time conversion as well. I’m unsure how it works but in your polling script, you could do something like:

<div wire:poll>
    <local-time datetime="2014-04-01T16:30:00-08:00">
        April 1, 2014 4:30pm
    </local-time>

    <script>refreshTime();</script>
</div>

The refreshTime() script pseudo code for the action time-elements takes to find all the local-time elements and propagate the local time from utc. I didn’t dive too deep into the time-elements package so I’m unsure what that code looks like.

Alternately, you can have javascript set a livewire variable to the local time offset and calculate that in the backend then just dump out the Carbon time calculating the offset on polling:

component.blade.php

<div>    
    <div wire:poll>
        <local-time datetime="{{ $timestamp }}"> <!-- format timestamp Carbon instance as you see fit -->
            {{ $calculatedReadableTimestamp }} <!-- format calculated timestamp Carbon instance as you see fit -->
        </local-time>
    </div>

    <script>
        var d = new Date();
        var offset = d.getTimezoneOffset(); //gets offset in minutes

        @this.set('timeOffset', offset); //sets the time offset in livewire;
    </script>
</div>
Component.php

public $timestamp;
public $calculatedReadableTimestamp = '';
public $timeOffset;

public function mount()
{
    // set $timestamp to some Carbon\Carbon instance
}

public updatedTimeOffset() // will fire off when $timeOffset is updated
{
    $this->calculatedReadableTimestamp = $timestamp->copy()->addMinutes($timeOffset);
}

The only downside here is that your initial load will be either server time, utc, or blank depending on how you want to handle it but refresh should be quick. You could store the offset to session and only have to set it once for the duration of your app.

Alternately, there might be something within the time-elements package that will poll <local-time> elements and make sure they’re kept current but again, I didn’t dive too deep into the package.