Live View - Is there a way i can know whether I come from direct link vs liveview link?

Sorry for the noob question,
Is there a way i can know whether I come from direct link vs liveview link? Both will be pick up by handle_params so how do I differentiate it?

I inspected all the arguments in mount and handle_params for a live_link and redirect link and they are pretty well identical so I don’t think you could differentiate without doing something yourself. It’s a little ugly, but something like:

live_link(class: "nav-link", to: Routes.live_path(@socket, MyAppWeb.LiveThing.Index, %{from_live: true}))

and then

def handle_params(%{}=params, _uri, socket) do
  from_liveview = case params["from_live"] do
      "true" -> true
      _ -> false
    end
  {:noreply, socket}
end

Easy enough for a user to override if they want because the parameter can be put in the URL, and it looks a bit ugly on the browser address bar.

What’s the use case? Maybe there’s another approach altogether.

Can you elaborate on your use case for differentiating the two?

That is almost like what I did. I check for value in the socket instead. My use case is I’m building a website that fetch directory from github api. I don’t want to fetch the api each time from live_link since the value is already in the socket. So I only want to fetch the directory if it’s a direct link. You can view my site here for example. Awesome Site .

So could you just fetch the directory from github api if the value isn’t already set? That’s really what you’re wanting by the sounds of tings.

e.g. something like

def handle_params((%{}=params, _uri, socket) do
  github_directory= case socket.assigns[:github_directory] do
    nil -> get_github_drectory()
    value -> value
  end

  assign(socket, github_directory: github_directory)
 ...

Yeah that is what I’m already doing. I just thought that there would be another way :smiley:

1 Like