Hotwire Discussion

User like system

Hello :slight_smile:,

I would like to do a user like system but I have no idea how to do it.

I click on the heart to the right of the name. The heart turns red. I click again on the same heart, it turns gray.

If there is an error during the request related to multiple reasons, I would like to display a modal with text telling it to reload the page.

The liked user must be alerted in real time that he has been liked.

Thank you for your help :slight_smile:

It would be helpful if you could describe what sort of tools you’re currently using. Is this on Rails? Are you using Turbo and/or Stimulus?

In general, you can think of the heart like a button for a form with hidden inputs for both the user who’s clicking and the user whose photo is being liked. When clicked, on the back end, if the association between the two users doesn’t already exist, add it (liked); if it already exists, remove it (unliked).

If you’re using Turbo, you can wrap the heart button in a Turbo frame which is reloaded on submit. In your template, just check whether the like association exists and choose the appropriate icon/style.

The user notification can be done by broadcasting to a Turbo stream. But again, not knowing what you’re using or even what kind of app this is, it’s hard to be specific. Likewise for the modals.


I use Symfony, Stimulus and Turbo.

Thank you.
Should I use events turbo:submit-start and/or turbo:submit-end?

I’ve never used Symfony, so I have no idea how you’d handle that on the back end. The error handling doesn’t sound like a Turbo or Stimulus-specific problem, though. This is more basic application logic. If you submit a regular form and there are errors, how are you handling them?

You can check out this post for inspiration about handling form submissions, even if it’s with Rails.

Really, though, if you need help, it makes sense to post some code you’ve tried. What you’ve given us so far are just specs.

There are a couple of ways you could implement something like this. If the card is wrapped in a Turbo Frame, you could add a form for the like button. The form would post to a /posts/likes passing the post ID and would re-render the card with the red button, which would automatically replace the matching Turbo Frame.