Looking to create a simple function in Phoenix

Back to my orginal project , I used this as my alias

defmodule Test do
  alias TestWeb

  def broadcast(message) do
    Endpoint.broadcast!("room:lobby", "new_msg", %{body: message})
  end
end

Does this look correct? Maybe I can trying the wrong commands in the iex shell?

I seemed to have been in the wrong directory sorry for the confusion! This is my current error when I run it, believe it is the wrong alias

iex(1)> Test.broadcast("hello")
** (UndefinedFunctionError) function Endpoint.broadcast!/3 is undefined (module Endpoint is not available)
    Endpoint.broadcast!("room:lobby", "new_msg", %{body: "hello"})

Like this… the alias is for the Endpoint.

defmodule Test do
  alias TestWeb.Endpoint

  def broadcast(message) do
    Endpoint.broadcast!("room:lobby", "new_msg", %{body: message})
  end
end

I think it worked!

iex(1)> Test.broadcast("check")
:ok
iex(2)> 

Seems like nothing is showing up on my chat frame though, any idea how to track this from here?

I use chrome dev tools, network panel.

Test.broadcast("message from server")
:ok

It says okay but nothing seems to be showing in my network tab!

I have placed a console.log in my channel.on

channel.on("new_msg", payload => {
    console.log("I am here");
    let messageItem = document.createElement("li")
    messageItem.innerText = `[${Date()}] ${payload.body}`
    messagesContainer.appendChild(messageItem)
})

Only seems to be hitting when I am typing in the browser and not when I am calling from my iex.

Make sure you are starting iex similarly to iex -S mix phx.server (and not running an iex instance that is separate like a plain mix phx.server

2 Likes

Why is your token undefined in your screenshot? And websocket marked as pending too…

1 Like

hm not sure! But it started working when I tried axelsons suggestion to run iex -S mix phx.server!

1 Like