This episode is for members only

Sign up to access "Build a Livewire Comment System" right now.

Get started
Already a member? Sign in to continue
Playing
08. Listening to events with Alpine

Transcript

00:00
you've probably noticed that when we post a reply to a comment and hit reply, sure enough that gets stored in the database but we don't see this toggled off. So let's fix that up now with an
00:14
event from Livewire which we can pick up in Alpine. Okay so let's go over to where we are actually replying. The first thing that we're going to do is dispatch this event. Let's go ahead and call the dispatch method on this component. Let's give this a name. We'll just call this replied for now. Now optionally we can pass through any arguments to this so we might at some point need the comment
00:38
that was replied to. For example if we want to flash a message. So let's pass that in now even if we don't need to. We could also go ahead and use an array here to give the reply as well if we need it. Okay so now that we are dispatching an event, once we create a reply this will be dispatched and we can pick it up using Alpine. If we head over to the comment item component
01:01
let's go up to the top where we have our state. From here we can say x on and then we can give the name of the event. So let's say replied. Now because this is an event and we need to pick it up on the global window object we need to use the window modifier. Once this event comes through we can just access any of the data that we're storing in this component and set it
01:24
to whatever we need. So we're always going to assume that when we are replying we just want to set replying back to false. So that will toggle the state off. Let's go over to the browser and check this out. Okay so I'm going to say a new reply. Hit reply and yeah there we go. Our replying state is now toggled off.

Episode summary

In this episode, we tackle a small UI problem: when we post a reply and hit reply, the state doesn't automatically reset and the reply box stays open—even though the reply is stored in the database. To make things feel smoother, we set up an event system so the UI updates right away.

We start by dispatching a custom event from our Livewire component every time a reply is created. We call this event replied, and send along any data we might need (like which comment was replied to). Even if we don't need it now, it's handy to have.

Next, over in our Alpine component that's used for each comment, we listen for this replied event on the global window object using Alpine's x-on:window syntax. When the event comes through, we set the replying state to false, which hides the reply box.

Finally, we jump into the browser to test it out. Posting a reply now closes the reply box as expected. This quick change helps keep the frontend and backend nicely in sync, all with just a little bit of event wiring between Livewire and Alpine.

Episode discussion

No comments, yet. Be the first!