How to switch language on pages with variables in route?

Hello everyone, I’m new to programming and also to liveview. And I met an issue while setting language with my navigation component. Switching button works correctly until there are some :atoms in routes. How can I make it work correctly everywhere?

Here’s my code

 def handle_event("change_lang", %{"lang" => lang}, socket) do
    socket = assign(socket, :lang, lang)
    {:noreply, redirect(socket, to: Routes.live_path(socket, socket.view, locale: lang))}
  end

So I think it conflicts with my variables in route, but how to solve it?

Thanks for reading (and for help also)

You could implement handle_params, retain the URI from there and just switch out the locale query parameter on it.

Thanks! I tried to solve it in that way, but met the problem with invoking that handle_params. My uri isn’t assigned though it was actually done in that handle_params before changing language handle_event. Probably I missed something but still can’t get what exactly.

Maybe adding code will be helpful

def mount(socket) do
    {:ok, socket}
  end

  def update(assigns, socket) do
    email = assigns.current_user.email
    socket = assign(socket, :email, email)

    {:ok, socket}
  end

  def handle_params(_params, uri, socket) do
    IO.inspect(uri, label: "uri")

    {:noreply, assign(socket, :uri, uri)}
  end

  def handle_event("change_lang", %{"lang" => lang}, socket) do
    socket = assign(socket, :lang, lang)
    {:noreply, live_patch(socket, to: "#{socket.assigns.uri}/?locale=#{lang}")}
  end

Inspecting uri also does nothing, I have no idea how to implement it

handle_params is only invoked on router mounted liveview. So make sure this code is not a nested liveview or component.

oh, thank you, now I see. That is exactly component. So, maybe, there is no way to solve it :frowning:

The parent can pass its url into the component. This just doesn‘t happen automatically.