Recommended pattern for this use case

Hi!

I’m pretty new to Hotwire. I have a use case which I’d like to know what would be the best approach to implement it. Thanks on beforehand for your help.

I have a form with an input. The input accepts an URL and once the URL looks to be valid (client side) I’m making a fetch request to retrieve some information (target URL’s metadata such as title, size, etc…) and once I get this information, I use that information to conditionally show other fields, enable or disable buttons, etc.

So far this works great.

The problem I have, is that once you submit the form, if there were server validation errors, the form shows the error but I’ve lost the metadata I had fetched dynamically on the client side, so the form is broken.

I bet I’m not doing this in an idiomatic way. What would be the best way to accomplish this, so I don’t have to duplicate the form logic both in the backend and in the frontend, or handle the “special case” of the form having errors, etc?

Thanks for your help.

Hi @caseb, since you’re fetching the metadata in the user’s browser you could create hidden fields for that metadata (if it’s well defined). Then, when the form is submitted, you’ll get the metadata back in those hidden fields. You’d have to either allow the metadata parameters on your model if you’re eventually storing it, or just use hidden_field_tag 'metadata[title]', params.dig(:metadata, :title) to temporarily use it in the request cycle.

I assume you’re using Stimulus for your front-end functionality. If so, when the controller reconnects, you could tell it to find any pre-existing metadata in these fields and act accordingly.

There are other ways to skin it too. You could just have one hidden metadata field (taking the whole JSON string) and then redisplay the metadata in a data-controllername-metadata-value attribute that your controller can use when it connects.

Hope that helps :smiley:

Hi @brendon , thanks a lot for answering.

The problem is that I can’t get the metadata until the user fills in the first input, which is an URL I’ll be getting the metadata for.

I think the big problem I’m having here is that I’m relying too much on Stimulus. I’ll try to reimplement this by submitting the form, or part of it, and relying more on turbo streams/frames.

Wish me luck :stuck_out_tongue:

Thanks for your help.

I think that’ll still be ok. You can initialise your stimulus controller with empty defaults for the metadata and then populate the hidden field the first time you fetch the metadata. Then submit it to the server and pump it back into the data attribute of the controller on page redisplay. You can attach a change callback to the metadata value to mutate your interface as needed when the metal changes: Stimulus Reference

Good luck! :smiley:

1 Like