#Get current URL Path from app layout ?

28 messages · Page 1 of 1 (latest)

celest oyster
#

Ah my mistake.

#

Did you check whether your hook is called?

magic dune
#

When I inspect the output of attach hook after calling on mount, I cant see the assigns field in the socket... but I see the log

celest oyster
#

So you places the dbg() in the assign_current_path or on_mount?

#

You won't get the assigns on on_mount, you will only get them set when assign_current_path is invoked. You mention seeing a log, where abouts was it?

#
defmodule MyAppWeb.LiveHooks do
  import Phoenix.Component, only: [assign: 3]
  import Phoenix.LiveView, only: [attach_hook: 4]

  def on_mount(:global, _params, _session, socket) do
    # Or here?
    socket =
      attach_hook(socket, :assign_current_path, :handle_params, &assign_current_path/3)

    {:cont, socket}
  end

  defp assign_current_path(_params, uri, socket) do
    # Is it here?
    uri = URI.parse(uri)

    {:cont, assign(socket, :current_path, uri.path)}
  end
end
magic dune
#

def on_mount(:assign_current_path, _params, _session, socket) do
socket =
attach_hook(socket, :assign_current_path, :handle_params, &assign_current_path/3)
|> IO.inspect()

{:cont, socket}

end

celest oyster
#

Yup, so that's not going to have the assign

magic dune
#

either works to see the reference. I can also see the uri log when I log it

celest oyster
#

The assign should be placed in assign_current_path

#

Can you determine that putting your IO.inspect() or dbg() in the defp assign_current_path(_params, uri, socket) do block prints?

magic dune
#

yeap

%URI{
scheme: "http",
authority: "localhost:4000",
userinfo: nil,
host: "localhost",
port: 4000,
path: "/dashboard/Efe",
query: nil,
fragment: nil
}

#

I also have other on_mount functions which makes checks and assign/redirect and they work

#

but the attach hook seems not to work,

celest oyster
#

If it is printing, the attach_hook is working, otherwise your URI inspect wouldn't have been printed.

magic dune
#

but not assigning to the socket

celest oyster
#

Okay, what about this then:

defp assign_current_path(_params, uri, socket) do
    # Is it here?
    uri = URI.parse(uri)

    {:cont, dbg(assign(socket, :current_path, uri.path))}
  end
#

What do you get here?

magic dune
#

yeap I see the current_path on dbg log

#

but on my app layout, @current_path throws error

celest oyster
#

What's your layout like? So provide the path of the layout file itself please.

magic dune
#

ahhhhh damn Im so stupid

celest oyster
#

Because you haven't done anything wrong with your hook, it definitely looks right.

magic dune
#

I forgot to pass the value to my component !!

celest oyster
#

Haha, I thought that might be the case.

#

One of those days

magic dune
#

Thanks mate and sorry for your time 😄