Search code examples
websocketelixirphoenix-frameworkphoenix-live-view

The data of assigns gets lost when a button is clicked in a modal


I save "current_user" to the session variable in a plug. And I have the standard, auto-generated form-component or modal of LiveView. I'm using a modal in a part of a website where only authenticated users are allowed.

router:


    live_session :on_authenticated, on_mount: MyWebsiteWeb123.InitLiveassignss do
      scope "/", MyWebsiteWeb123 do
        pipe_through :browser

        live "/abc", MyLive
      end
    end

init assignss module:


    defmodule MyWebsiteWeb123.InitLiveassignss do
      import Phoenix.LiveView

      def on_mount(:on_authenticated, _params, session, socket) do
        cu = Repo.get!(User, session["current_user_id"])
        socket2 = assigns(socket, :current_user, cu)

        {:cont, socket2}
      end
    end

This nicely allows me to get access to the current_user in socket in the situations when "submit" button is clicked, in a normal form on a page.

However, not in a modal. That is, not when "save" button is clicked in it -- 'current_user' gets dissapered.


    //current user is nil
    def handle_event("save", %{"my_model" => my_model_params}, socket) do
      // 'current_user' doesn't exist anywhere in 'socket'
      a1 = socket.assigns[:current_user]

      //
      //a2 = socket.assigns[:current_user_id]
      //a3 = socket.assigns["current_user"]
      //a4 = socket.assigns["current_user_id"]
      //a5 = socket["current_user_id"]
      //a6 = ...........

      //......
    end

Where has current_user has disappered from assigns in a modal?

How to make all this work?


Solution

  • So since it's a live component. Follow this. Namely:

    <.live_component module={YourLiveComponent} id="live-component-id" current_user={@current_user} />
    

    you can call @current_user because HEEX's assigns from live view is defined by your on_mount.