In this episode, we're tackling the challenge of adding new posts and making sure that our UI updates automatically when you do. We start by building a brand new form component for creating posts—keeping things modular and organized. You'll see how we create a textarea blade component (since our starter kit didn't have one yet), add validation, handle errors, and set up the submission flow with Livewire actions.
Once the basic form is up and running, we dig into the trickier part: making sure the list of posts actually updates reactively when a new post is created. Initially, even after submitting a new post, it doesn't appear in the list until you refresh the page. That's because our components are separate, and the reactivity isn't flowing between them by default.
To solve this, we start dispatching a Livewire event from the creation component and listen for it in the post index component. When we get the event with the new post's ID, we prepend it to the post list—making sure to handle edge cases when there are no posts yet. However, we notice that even after updating the array, the UI still doesn’t change. This is a classic reactivity gotcha: Livewire won't re-render unless the child component knows it needs to be reactive.
The quick fix is to add the reactive
attribute to the relevant component, which finally gets our UI to update instantly as soon as you add a post. But, as we discuss (and will dive deeper into later), making everything reactive isn't always the best long-term approach due to possible over-rendering and performance issues—so this is an important lesson in balancing reactivity and efficiency.
By the end, you’ll have a working create-post flow that's reactive, understand how event dispatch and listening works between Livewire components, and get a preview of the more advanced optimizations we'll cover as the course continues.