sodapopcan

sodapopcan

Passing assigns to LiveView JS Hook's `mounted` callback

Is there a way to pass initial values to a LiveView JS hook from the server?

Here’s my example LiveView:

defmodule FooWeb.PageLive do
  use FooWeb, :live_view

  @impl true
  def mount(_params, _session, socket) do
    {:ok, assign(socket, foo_assigns_i_want_to_reference_in_my_hook: %{bar: "hi"})}
  end

  @impl true
  def render(assigns) do
    ~L"""
    <div phx-hook="FooDomNode"></div>
    """
  end
end

And here is my JS hook:

let Hook = {}
Hook.FooDomNode = {
  mounted() {
    // Is there anyway I can access `foo_assigns_i_want_to_reference_in_my_hook` in here?
  }
}

// ... More JS boilerplate that properly passes `Hook` to `new LiveSocket(...)` and connects

As the commented part of the JS hook states: Is there anyway to reference the assigns of the LiveView mount in the JS hook’s mounted callback?

Thank you!!

Marked As Solved

sfusato

sfusato

There was recently added push_event/3 in 0.14.0 for pushing events and data from the server to the client.

Also Liked

Lango

Lango

How exactly would this work? I’m assuming the answer to the question is ‘no’ you can’t access it from the mounted event?

In my mind I would need to do something like this:

  1. Liveview loads
  2. Mounted callback is triggered
  3. Server somehow knows that mounted was called (perhaps by mounted sending a message?)
  4. Server pushes an event to everyone

Is that correct? Or am I way off base here

cmo

cmo

There are a few ways of communicating back and forth. The aforementioned push_event, the aforementioned assigning to a data attribute and reading it, e.g.

  def render(assigns) do
    ~L"""
      <div
        id="colorpicker-<%= @id %>"
        phx-hook="ColorPicker"
        phx-update="ignore"
        data-target="<%= @target %>"
        data-value="<%= @color %>"
        class="<%= @class %>">
        <input id="colorpicker-<%= @id %>-input" type="color" name="<%= @name %>">
      </div>
    """
  end

and hook:

Hooks.ColorPicker {
  value() {
    return this.el.dataset.value;
  },
  mounted() {
    this.picker = new ColorPicker({
      value: this.value(),
      enableOpacity: false,
      mode: "Palette",
    });

    const target = this.el.getAttribute("id") + "-input";
    this.picker.appendTo("#" + target);
  },
  updated() {
    this.picker.value = this.value();
  },
};

You see the data-value attribute in the render function is picked up in the value() function on the hook. data-value in the Hook’s tag is picked up by this.el.dataset.value.

See Phoenix LiveDashboard chart code which does this.

You can then send things back to the server with pushEvent and pushEventTo if you need.

Something like this:

    // listen to event: color changed in picker
    // this.picker.addEventListener("change", (e) => {
    //   this.pushEventTo(this.el.dataset.target, "set_color", {
    //     id: this.el.getAttribute("id"),
    //     color: e.value,
    //   });
    // });

Where Next?

Popular in Questions Top

9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New
chrisalley
ExUnit now has describe blocks which is a welcome addition coming from RSpec. In the docs, it states that nested hierarchies of describe ...
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lists...
New
LegitStack
I’m trying to make a websocket server in Phoenix or raw Elixir. I heard about gun, I think I could use cowboy, but since I’m not that sma...
New
Emily
I have VueJS GUIs with the project generated using Webpack. I have Elixir modules that will need to be used by the VueJS GUIs. I forese...
New
nobody
Hi! In PHP: $_SERVER[‘SERVER_ADDR’] - in Elixir? Searched the docs for ip address and the web, no good results. Thanks!
New
earth10
Hi, I’m just starting to build a side-project with Elixir and Phoenix and doing some basic test with Elixir alone. What strikes me is th...
New
jononomo
For some reason my phoenix channels are working for me in my local dev environment, but as soon as I deploy via Docker, I get a 403 error...
New
svb
Hi! Currently I want to submit a form by pressing the Enter key. However, since my input field is of type “textarea” this is just adds a...
New

Other popular topics Top

johnnyicon
Hi all, I’ve just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I’m trying to use Postgres...
New
msaraiva
Surface is an experimental library built on top of Phoenix LiveView and its new LiveComponent API that aims to provide a more declarative...
564 43757 214
New
aesmail
Hello guys, I have finally made it. I created an admin interface for a framework. It’s been on my todo list for years and with the curre...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New
RisingFromAshes
I’ve read in another post that it may be possible with a router helper - but I couldn’t find an appropriate one, and tbh, I’m still just ...
New
dblack
I’ve got an issue with an app and I’ve no idea of how to troubleshoot it. I’m hoping someone here might have seen something similar. I p...
New
komlanvi
Hi everyone, I was playing with phoenix liveView but I run into an issue. I have a form and want to validate each input text when the te...
New
Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New
dokuzbir
I want to highlight html closing tags when i click a html tag. That works in .html files but doesnt work for html.eex templates. How can...
New

We're in Beta

About us Mission Statement