Problem with liveview

Problem with liveview

I’m adding liveview to my project,
however it is not working.

I made a basic example to test liveview, but when clicking the button n does nothing.

code liveview

  def render(assigns) do
     ~L"""
     <button phx-click="docker_start_container" phx-value-id="my-test">TEST</button>
     """

  end

  def mount(_params, %{"current_user" => user_id}, socket) do
    if connected?(socket), do: Process.send_after(self(), :update, 3000)

    socket =
      socket
      |> assign(:current_user, user_id)
    {:ok, socket}

  end

  def handle_event("docker_start_container", %{"id" => id}, socket) do
    require IEx; IEx.pry

    {:noreply, assign(socket, id)}

  end

app.js

import NProgress from "nprogress"
window.addEventListener("phx:page-loading-start", info => NProgress.start())
window.addEventListener("phx:page-loading-stop", info => NProgress.done())
import {Socket} from "phoenix"
import LiveSocket from "phoenix_live_view"

let csrfToken = document.querySelector("meta[name='csrf-token']").getAttribute("content");
let liveSocket = new LiveSocket("/live", Socket, {params: {_csrf_token: csrfToken}});
liveSocket.connect();
window.liveSocket = liveSocket;

endpoint


  socket "/live", Phoenix.LiveView.Socket,
  websocket: [connect_info: [session: @session_options]]

mix

{:phoenix_live_view, "~> 0.14.4"}

version

elixir 1.10.4 (set by /home/user/.tool-versions)
erlang 23.0 (set by /home/user/.tool-versions)

I made all the settings that the documentation asked for, but it still doesn’t work

When I go to inspect through the browser, it returns this to me

image

Can you help me, how to solve this problem?

It’s not really a LiveView issue. You’re seeing a JS error. What it’s telling you is that it expects a meta tag with a CSRF token but it didn’t find one. If you look in the default layout Phoenix generates, you’ll see that in the head.

See L7 here: https://github.com/phoenixframework/phoenix/blob/master/installer/templates/phx_live/templates/layout/root.html.leex

I just forgot to put this in the body of the message

I also put it inside the

app.html.eex
<% = csrf_meta_tag ()%>
And yet the problem remains.

I will need to create another layout named root.html.eex and add this meta?

I just found out where my mistake was.

in router.ex

needed to add the
plug: put_root_layout, {MyprojectWeb.LayoutView,: root}

in

   pipeline :protected do
   end

With that the problem was solved.

Thank you