Add / Remove Filter Params From URL In LiveView

I want to only add the filter parameters in the URL when the user actually uses the filter, but right now they are part of the URL since I added them in handle_params.

like this http://localhost:4000/products?page=1&per_page=5&min=&max=

when I use I fire the handle_event for filtering it will be like this:

http://localhost:4000/products?page=1&per_page=5&min=500&max=1700

@impl true
  def handle_params(params, _url, socket) do
    page = String.to_integer(params["page"] || "1")
    per_page = String.to_integer(params["per_page"] || "5")

    paginate_options = %{page: page, per_page: per_page}

    min = params["min"] || ""
    max = params["max"] || ""

    filter_options = %{min: min, max: max}

    products = Products.list_products(paginate: paginate_options, filter: filter_options)

    socket =
      assign(socket,
        options: paginate_options,
        filter: filter_options,
        products: products
      )

    {:noreply, socket}
  end
def handle_event("filter", %{"min" => min, "max" => max}, socket) do

    socket =
      push_patch(socket,
        to:
          Routes.products_index_path(
            socket,
            :index,
            page: socket.assigns.options.page,
            per_page: socket.assigns.options.per_page,
            min: min,
            max: max
          )
      )

    {:noreply, socket}
  end

How do I append the filter parameters in the URL when the user is only using the filter functionality?

May be a late answer, but hopefully useful for some who comes later. If you don’t mention min or max as a keyword list when constructing the URL (or using ~p sigil, then they don’t appear in the url at all.

The idea is (with a filter as an example):

params =
  case filter do
      "" -> %{}
      _ -> %{filter: filter}
  end
{:noreply, push_patch(socket, to: ~p"/path_to_resource?#{params}")}
1 Like