In this episode, we're tackling a pretty common headache when dealing with multi-step forms: what happens when the user goes back to previous steps to edit something they've already entered! Things can get messy fast—like losing the state of form fields, in this case, the uploaded image, which just disappears or makes the form misbehave.
We start by re-tracing the steps of creating a product, focusing especially on uploading an image. Then, we test what happens when we go back and forth between form steps. You'll notice the image preview doesn't stick around as expected, and weird things start to happen with validation and navigating to the next step.
To fix this, we start by implementing a computed imagePreview
property. This smart little property checks if there's a temporarily uploaded image to show, but also falls back to the already-stored product image if there isn't. So, now, when you go back to the image upload step, it still shows the image!
Next, we update the logic that handles moving between steps—so if there's already a product image, we just let the user continue instead of nagging them to re-upload the image. Along the way, we realize we're making too many database requests every time the form checks the product state, so we introduce another computed property to keep everything efficient by caching the product info within the component.
To double-check for extra queries, we pull in Laravel Debugbar and clean up our computed properties until we're at a single query for these operations. Then it's time to quickly review and live-test everything, making sure the fixes work and reviewing the code one more time for clarity.
We wrap up by noticing some edge case issues (like how temporary uploads sometimes get wrapped in arrays by the package we're using), and we set up a segue for the next episode, where we'll solve those pesky state management problems once and for all.