nduitz

nduitz

Hey there.
I don’t know if this is intended behaviour, thus I wanted to open a discussion here before opening a bug report.
I tried to conditionally register a phx-hook (I have a timeline that under certain circumstances should be sortable).
I created a demo of the behaviour here: phx-hook-demo/lib/demo_web/hook_demo_live.ex at main · nduitz/phx-hook-demo · GitHub

To break it down:
Simply changing the value to enable does not do the trick (phx-hook={@enabled? && "SomeHook"}). However changing the id along with the enabled assign would invoke the mounted() callback of the hook: id={@enabled && "hooked" || "unhooked} phx-hook={@enabled? && "SomeHook"}

It seems that this behaviour exists for fair reasons but I think the documentation could be more explicit about this.

WDYT?

Showing Posts 1 to 10

Phxie

Phxie

I assume you can’t toggle hooks via buttons because they are triggered by mount/update.

You could just connect the hook regardless, and have a data-attribute={@condition} on the hook element then check the data-attribute for true or false and run the code based on the outcome.

sodapopcan

sodapopcan

This doesn’t sound like a bug to me. You said it in your answer, but the hook isn’t going to active because the JS is only activated on mount. Changing id is a possibly lesser known trick to cause a component to remount.

garrison

garrison

My first instinct was to agree. But what happens if you do this?

<%= if @foo do %>
  <div id="foo" phx-hook="MyHook" />
<% else %>
  <div id="foo" phx-hook="OtherHook" />
<% end %>

Or this?

<%= if @foo do %>
  <div id="foo" phx-hook="MyHook" data-foo="bar" />
<% else %>
  <div id="foo" phx-hook="MyHook" data-hello="world" />
<% end %>

If changing the hook doesn’t remount the hook, then either both of these must trigger remount or neither must. And I’m not sure if either of those options feels correct to me.

Intuitively I would expect the hook to behave like a component, remounting if it has changed (id or phx-hook has changed), which is also clearly what the OP was expecting. Requiring the id to change is violating the declarative behavior of the API and forcing you to write imperative code (to update the id) in order to update the result, which will cause bugs.

sodapopcan

sodapopcan

Hey fair enough! I’m coming from more of an XY place (without explicitly asking) as I’ve never run into this myself (nor have I ever changed an id).

garrison

garrison

I believe what’s actually going on here is that hooks (like LiveComponents) are tied to an id for their lifecycle, meaning you could probably “teleport” them anywhere in the page and they would remain intact if you did it in the same render batch. I don’t know exactly how the internals work, but I believe that’s the general idea.

This is distinct from how components work in, say, React, where the mount/unmount lifecycle is tied to the position in the DOM (and a key for dynamic children). TBH the React version is probably strictly superior, though there are some theoretical advantages for the id approach with LiveView since sending things over the wire is so expensive (i.e. you can pick up a whole subtree and move it).

But in the case of hooks this leads to surprising behavior, where changing the hook does not remount it. At least assuming the OP is correct - I have never tried this either. I think this probably could be fixed by detecting a hook has changed for a given id and remounting it, though again I don’t know the internals very well.

sodapopcan

sodapopcan

:hear_no_evil_monkey: alalalalalalalalalalalalala

Phxie

Phxie

It’s definitely not a bug though. OP’s issue is that they are just using Mounted and not using Updated.

let liveSocket = new LiveSocket("/live", Socket, {
  longPollFallbackMs: 2500,
  params: { _csrf_token: csrfToken },
  hooks: {
    DemoHook: {
      mounted() {
        console.log("demo hook mounted");
      },
    },
  },
});

The issue is solved in your example and fits perfectly with Liveviews lifecycle already.
The below makes the div code modular, and will always trigger an Updated() diff due to the conditional rendering.

<%= if @foo do %>
  <.live_component module={Component} id={"id"} hook="newHook" />
<% else %>
  <.live_component module={Component} id={"id"} hook="OtherHook" />
<% end %>
  use AppName, :live_component    

  def render(assigns) do  
    ~H"""
      <div id="hook" phx-hook={@hook}>
nduitz

nduitz OP

I will try that but in my example adding an updated callback won’t solve the issue. Neither is fired when I add the hook conditionally

Phxie

Phxie

I didn’t mean to imply that updated() would fix your specific example in its current state. From the looks of it, the issue is that you aren’t doing anything that actually effects the DOM in the non working part, but changing the ID in the working part causes the component to remount.

I meant to show how I would do it for the issue you’re trying to solve. I would create a live_component, pass the hook as an attribute as either a string or nil, then conditionally render the components with whatever your ID system is. I don’t know your exact use case, but if you’re toggling hooks on and off then using mounted() and updated() sounds like it makes more sense to me. But again, don’t know the exact use case so I’m assuming based on the toggle button. I may have jumped the gun on suggesting updated() if your plan is to load one or the other rather than toggle between them frequently in the same session. But still, I would make it a conditionally rendered component rather than add conditions to the hook/ids personally.

Where Next? Top

Trending in Discussions Top

AstonJ
As the title says, please share what you’ve been up to with Elixir. Whether that’s been learning it, looking into it, making stuff with i...
2977 92995 915
New
AstonJ
The obligatory hello world thread! Who are you and where are you from? :stuck_out_tongue:
4616 55835 594
New
caslu
I want to open this thread for you all to discuss and help those who really like Ash but are still hesitant to use it in a real project. ...
New
arcanemachine
I was working on an Ecto migration and I needed a timestamp. So, for the nth time, I looked up the different data types for timestamps, a...
New
alexslade
Fly’s CEO posted this recently - Turn And Face The Strange · The Fly Blog It says that Fly is going all-in on sprites, which is a worry ...
New
Herve37
We’re evaluating API mocking tools for OpenAPI-based projects and would love to hear what other teams are using. We’re particularly inte...
New
matt-savvy
Is there a word for the ~> symbol used in Version strings? Do you also just call it a Squiggle Arrow™ ?!
New

Other Trending Topics Top

garrison
Hobbes is a low-level distributed database for the Elixir programming language. Hobbes provides a simple, safe, and scalable storage lay...
New
mcass19
ExRatatui lets you cook up rich terminal UIs in Elixir, powered by Rust’s ratatui via Rustler NIFs. Build interactive terminal applicatio...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge &amp; Solve. They are GUI (Emerge) and State management (S...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
wintermeyer
There are three potential reasons for members of this forum to have a look at https://vutuv.de You are tired or annoyed of LinkedIn. Yo...
New
webofbits
Aludel - LLM Evaluation Workbench Aludel is an embeddable Phoenix LiveView dashboard for evaluating and comparing LLM prompts across mult...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews