Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Phoenix Channel `push` ** (Protocol.UndefinedError) protocol Jason.Encoder

Whenever a user joins a channel, I want to send them a record of all the previous messages that were sent.

My implementation for handle_info below triggers this error protocol Jason.Encoder not implemented for Hello.Messaging.Message.

My guess is that messages is a list of structs, when it needs to be converted to a list of maps?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  use Phoenix.Channel
  alias Hello.Messaging

  def join("room:" <> room_id, params, socket) do
    send(self(), {:after_join, params})
    {:ok, assign(socket, :room_id, room_id)}
  end

  # push triggers the error message here
  def handle_info({:after_join, _params}, socket) do
    messages = Messaging.list_messages()
    push(socket, "messages", %{messages: messages})
    {:noreply, socket}
  end

  def handle_in("new_msg", %{"body" => body}, socket) do
    case Messaging.create_message(%{body: body, room_id: socket.assigns.room_id}) do
      {:ok, msg} ->
        broadcast!(socket, "new_msg", %{body: msg.body})
        {:noreply, socket}

      {:error, reason} ->
        {:error, reason}
    end
  end

 

>Solution :

Jason.Encoder is not implemented for structs, and your Hello.Messaging.Message is a struct.

If you own the struct, enable encoding for it as described in the documentation

@derive {Jason.Encoder, only: [....]}
defstruct # ...

If you cannot modify the struct, convert it to map with Map.from_struct/1.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading