Feature request: phx-hook for "inserted"

There are javascript hooks for mount, update, delete etc, but none specifically for insert.
Mount is called on each item when the page is first loaded, the proposed “insert” hook would only be called if a new item is inserted into the stream.

Hooks are about generic JS interop and not directly related to streams. The lifecycle events you describe are directly related to the node the hook is attached to, not its children.

That said, how do you have your hooks set up?

If your hook is attached to each item in the stream, then mounted is exactly what you want. mounted is called any time an element with an attached hook is added to the DOM, not just on page load.

If you have your hook on the stream’s container, then a custom event can get you what you’re looking for:

Hooks.StreamContainerHook = {
  mounted() {
    const streamContainer = this.el

    this.handleEvent("my-custom-event-name", ({ id }) => {
      const insertedNode = streamContainer.querySelector(`#stream_item_${id}`)
    }
  }
}
def handle_event("insert", _, socket) do
  new_item = %{id: 1, name: "Some item"}

  socket =
    socket
    |> stream_insert(:my_stream, new_item)
    |> push_event("my-custom-event-name", %{id: new_item.id})

  {:noreply, socket}
end
1 Like

If you put a hook on the stream items, the mounted callback would be fired for each added item, so you effectively have what you’re asking for already :slight_smile:

4 Likes