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.