In this episode, we're tackling a common UX detail: making those relative dates (like "2 minutes ago") automatically update themselves as the user sits on the page. Out of the box, we noticed these dates only update when Livewire refreshes the data—like when we add a new comment or perform some other action—but otherwise, they just get stale.
So here's what we do: First, we decide to create an Alpine.js directive (or plugin, as you hear it called) that will handle this process on the client side. We go through setting it up, making sure Alpine is ready for our custom directive, and registering everything inside our app.js file. We also set up our comment blade to include a proper datetime attribute.
Once the directive is hooked up, we use Day.js (a slick date manipulation library) to format these timestamps into readable relative dates. This involves pulling in and extending Day.js with the relative time, timezone, and UTC plugins, because we want the times displayed correctly no matter where the server or the user is.
After the initial transformation, we go a step further and set up a setInterval
within our directive so that every 30 seconds, the displayed relative times are refreshed. This means the "a few seconds ago" turns into "a minute ago", and so on, all without the user needing to reload or trigger any events.
By the end of this video, you'll have a user interface where all comment timestamps update live and smoothly, giving your app that polished, modern feel!