Stimulus/Rails sorting

I’m using Rails/Stimulus/Turbo.

I have a simple scheduling app with a UI that has tabs for every day of the week. On initial load (using a Stimulus controller), all the items are loaded into the DOM inside a turbo frame, but only the items for the current day are shown. If you click a day, the controller swaps that day’s items in with CSS classes and hides the rest. This works fine.

It’s a schedule, so obviously I’d like to keep the items sorted on create/update. The obvious solution for that is to use target="_top", but then I lose state. If I want to, for example, switch tabs to the day of the last item created, I lose reference to that with the refresh. Likewise for updating. In other words, I can reload the entire list of items that comes in sorted, but it’s just like starting with the initial page load, where the day selected is today.

Without “_top”, I actually managed to sort in place on edit by grabbing the form data and updating the attributes on the item accordingly, where it then gets toggled into view with CSS as described above. On create, however (using after_create_commit { broadcast_prepend_to “items” }), the item is inserted after the submit event and so it’s not available to be sorted in place. At least, I can’t figure out how to listen for the item being inserted into the DOM in order to grab its id and sort it in place like I did with edit.

My original, pre-Stimulus approach involved just passing the object’s day parameter from the Rails controller (sorry), but as I’m trying to learn Stimulus well, I’d rather avoid it (same goes for sessions, which I’ve seen some people using). I’ve tried dispatching events to an external controller (both with and without targeting “_top”) and storing the day on that, but I just ended up confused as to how to read the state back into the main controller.

I’m sure I’m overthinking this. Basically, I’d just like to know whether it’s possible to persist that day value using Stimulus, or if it would be better just to handle it with Rails like I was doing.

Thanks.

Hi,

A feasible solution to your problem can perhaps be found in the following comment by DHH himself:

Thanks for the reply. I saw DHH’s post when I was first looking for solutions, but rolling my own mutation observer seemed a bit backwards. Having thought about it again–and seeing no responses with alternative suggestions–I guess it’s the best approach for now.