Hacker News new | ask | show | jobs
by nickjj 2007 days ago
> You just do LiveView instead of a regular controller. No duplication.

Yes but this is only in the happy case when the client is fully enhanced no?

What happens if you hook up a phx click event to increment a like counter.

After the page is loaded, if you click the + to increment it while having JavaScript disabled it's not going to do anything right?

But with Hotwire Turbo, if you have a degraded client with no JS, clicking the + would result in a full page reload and the increment would still happen. That's progressive enhancement. It works because it's a regular link and if no JS intercepts it, it continues through as a normal HTTP request.

2 comments

Yes, the `phx-click` doesn't automatically get translated to a link or form submission. You can still design the page to work without javascript. For instance by having a "+" button be a normal form or link and then have phx-click intercept it when javascript is enabled. This can be done with one LiveView module without having to also have a separate regular controller.

One way to do it would be to in the `mount` function handle normal non-javascript params being sent and a `handle_event` function handle `phx-click`.

I don't know if there is already a way to have `phx-click` with fallback to HTTP in a less "manual" way. It should be possible to make.

I've found that the vast majority of clicky stuff I do leads to a URL change anyways, and these are just proper links to the new URL that LV then intercepts.

In your Counter example, it's true that for the 'degraded' version to work, the link would have to be a proper link and not a phx-click. But in the (IMO very unlikely) case where this fallback is necessary, solving it with a proper link/route does not require duplication, just a different approach.

What you would do is create a LiveView that handles both the initial page and the 'increment' route. If LV is 'on', it intercepts the click and patches the page. if LV is 'off', your browser would request the 'increment' route, and the same LV would handle all this server-side and still display the new, incremented counter.

The LV is both the server-side controller /and/ the client-side logic. That's part of what makes it so appealing, but, admittedly, also something that can take a while to wrap your head around.

I've more than once reflexively gone for phx-click solutions where the LV would receive the event and 'do' something, only to later realize that it would be much better to use a proper url/routing solution (where LV is still the 'controller'). In hindsight it's often a case of treating LiveView too much like just 'React on the server', basically.