Feature

Table Pagination with LiveView

Preview

A table with Phoenix LiveView pagination

NOTE I do a manual pagination from a list of 100 products. They are in memory and not read from the database. I could have used a pagination package for Ecto.

    all_products = Products.list_products()

    paginated_products = all_products |> Enum.chunk_every(@page_size)
    products_for_page = paginated_products |> Enum.at(page_number - 1)
    total_entries = all_products |> Enum.count()
    total_pages = paginated_products |> Enum.count()
lib/phoenix_features_web/live/components/table_simple.ex
defmodule PhoenixFeaturesWeb.Components.TableSimple do
  use PhoenixFeaturesWeb, :live_component

  alias PhoenixFeatures.Products

  def update(assigns, socket) do
    page =
      case assigns[:params] do
        %{"page" => page} -> String.to_integer(page)
        _ -> 1
      end

    {:ok,
      socket
      |> assign(assigns)
      |> assign(get_products(page))
    }
  end

  @page_size 10
  def path(socket, page) do
    Routes.demos_show_path(socket, :show, "table_simple", page: page)
  end

  def current_page?(page_number, idx) do
    page_number == idx
  end

  def first_page?(page_number) do
    page_number <= 1
  end

  def last_page?(page_number) do
    page_number >= @page_size
  end

  defp get_products(page_number) do
    all_products = Products.list_products()

    paginated_products = all_products |> Enum.chunk_every(@page_size)
    products_for_page = paginated_products |> Enum.at(page_number - 1)
    total_entries = all_products |> Enum.count()
    total_pages = paginated_products |> Enum.count()

    [
      products: products_for_page,
      page_number: page_number,
      page_size: @page_size,
      total_entries: total_entries,
      total_pages: total_pages
    ]
  end
end