sb logoToday I Learned

When to use the handle_params callback

The handle_params/3 callback is helpful for using the state in the URL to drive the presentation of your LiveView. This is nice because you can share the URL with anyone and see the same LiveView state. handle_params is invoked after mount or whenever there is a live navigation event. If your LiveView is changing state based on the URL, handle_params is the right place to assign values on your LiveView, as you will avoid processing both in mount/1 and handle_params/3. To trigger handle_params/3, push_patch/2 can be used server-side, while live_patch/2 will trigger handle_param/3 through a client-side interaction.

For example, imagine we want to use handle_params/3 to implement pagination, filtering, and sorting. Using these two examples, handle_params/3 can handle five different cases of URL state

  • only pagination /route?page=2&per_page=10
  • only filtering /route?filter=a
  • only sorting /route?sort_by=id&sort_order=asc
  • pagination, filtering, and sorting /route?page=2&per_page=10&filter=sneakers?sort_by=name&sort_order=asc
  • none specified (use defaults) /route
def handle_params(params, _url, socket) do
  paginate_options = %{page: params["page"], per_page: params["per_page"]}
  filter_options = %{filter: params["filter"]}
  sort_options = %{sort_by: params["sort_by"], sort_order: params["sort_order"]}

  shoes =
    Shoes.list_shoes(
      paginate: paginate_options,
      sort: sort_options,
      filter: filter_options
    )

  {:noreply,
    assign(socket,
      options: Map.merge(paginate_options, sort_options, filter_options),
      shoes: shoes
    )}
end

def handle_params(_params, _url, socket) do
  {:noreply, socket}
end