perceval62

perceval62

Need help linking a phoenix LiveView to a phoenix channel

I’m relatively new to phoenix, so I may not have the vocabulary to express myself clearly.
I ended up maintaining as a junior a phoenix application with different channels that each have subtopics.
Some new requirements came in and I opted to do that inside of a LiveView.
I would like to receive updates from a specific channel inside the LiveView, change the assigns and update some content that way.

defmodule MyApp.RoleBillboardLive do
  use Phoenix.LiveView
  import MyApp.{UserSocket, Endpoint}
  alias MyApp.Endpoint
  alias Phoenix.Socket.Broadcast
  def render(assigns) do
    ~H"""
    Message from server: <%= @param %>
    """
  end

  def mount(_params, _, socket) do
    topic = "global:test"
    MyApp.Endpoint.subscribe(topic)
    IO.puts("I am now subscribed to " <> topic)
    param = "This is a test,"
    {:ok, assign(socket, :param, param)}
  end

  #def handle_info(_, socket) do
  #  IO.puts("info")
  #  {:noreply, assign(socket, assign(socket, :yeet, "yote"))}
  #end

  @impl true
  def handle_info(msg, socket) do
    IO.inspect(msg)
    {:noreply, assign(socket, :param, msg)}
  end
end

When I run this code, the mount function is called, I can see it clearly in the terminal.
(I run the command iex -S mix phx.server)
The page loads as expected with the initial content,
but when i publish a message on the topic, handle_info is never even called

I tried to skim through the docs, and a few forum posts, but none of them seemed to be advising on what I’m trying to do.

Marked As Solved

benwilson512

benwilson512

Author of Craft GraphQL APIs in Elixir with Absinthe

No the code you sent connects you to a phoenix channel. This also uses websockets, but all it does is provide an API for javascript code to send events into and receive events from the server. LiveView (while implemented on top of channels) is distinct and requires its own JS. You can see an example here: phoenix_live_view_example/assets/js/app.js at master · chrismccord/phoenix_live_view_example · GitHub

If this is an existing phoenix application you’ll need to sort of “retrofit” channels to it which may be relatively challenging for a junior that is new to phoenix. You can find docs for this however here: https://hexdocs.pm/phoenix_live_view/installation.html

Nah don’t! There’s a lot here and you’re new!

Also Liked

kokolegorille

kokolegorille

You might have to check for connection

if connected?(socket) do
  ...
end
benwilson512

benwilson512

Author of Craft GraphQL APIs in Elixir with Absinthe

That is a great point. @perceval62 you really should do this in your mount/3

  def mount(_params, _, socket) do
    if connected?(socket) do
      topic = "global:test"
      MyApp.Endpoint.subscribe(topic)
      IO.puts("I am now subscribed to " <> topic)
    end

    param = "This is a test,"
    {:ok, assign(socket, :param, param)}
  end

When you first connect to a liveview app you get two calls to mount, one for the static render and one for the live render. I was actually just talking about this in another thread: More convenience functions to deal with assigns inside LiveView - #15 by benwilson512

benwilson512

benwilson512

Author of Craft GraphQL APIs in Elixir with Absinthe

Hey @perceval62 welcome!

Can you show the code you are using to publish? Also to confirm, you’re doing the publish call in the same iex session that is running the server, not a separate one right?

Finally in here:

  @impl true
  def handle_info(msg, socket) do
    IO.inspect(msg)
    {:noreply, assign(socket, :param, msg)}
  end

You should change that to assign(socket, :param, inspect(msg)) because otherwise if you get a message that isn’t a string it’s going to crash when it tries to render it.

Where Next?

Popular in Questions Top

sen
Hi All, I set a environment variables in dev.exs , like below code. when i start server, how can i set the ${enable} value? thanks. d...
New
lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
marius95
Hello everyone, I try to use an Javascript Event Handler in my root.html.leex file. Therefore I created a function in the app.js file: ...
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID&lt;0.412.0&gt; terminating ** (Postgrex.Error) FATAL...
New
mgjohns61585
Could someone help me? I’m making my first elixir program, number guessing game. I can’t figure out how to convert the user’s guess from ...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
jason.o
In the code below, if the create action is not set to accept “extra_key” as an input, it errors out with a message shown above. Is there ...
New
shijith.k
I am trying to start a new phoenix project with elixir 1.9, but mix phx.new does not work. It says that ** (Mix) The task "phx.new" could...
New
dotdotdotPaul
Okay, I’m having a heck of a time trying to figure out how to best handle the validation of belongs_to associations in Ecto. I’m sure I’...
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

Other popular topics Top

Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
marius95
Hello everyone, I try to use an Javascript Event Handler in my root.html.leex file. Therefore I created a function in the app.js file: ...
New
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
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
AstonJ
We’ve put together this wiki for Phoenix LiveView - please feel free to add any info you feel is worth including. What is Phoenix LiveV...
New
JakeBecker
TL;DR: I’ve just released an implementation of Microsoft’s IDE-independent Language Server Protocol for Elixir. It adds language support ...
1144 54120 245
New
jaysoifer
Is there a way to rollback a specific migration and only that one (“skipping” all the other ones)? Would mix ecto.rollback -v 200809061...
New
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New

Latest on Elixir Forum

Elixir Forum

We're in Beta

About us Mission Statement