State helper for the data_table/1 component.
Manages filter, sort, and pagination state in a single struct that lives in your LiveView assigns. All filtering and sorting happens server-side — you control the query.
Setup
alias AvenUI.DataTable
def mount(_params, _session, socket) do
{:ok,
socket
|> assign(:table, DataTable.new(per_page: 20))
|> load_rows()}
end
# Reload rows whenever table state changes
defp load_rows(socket) do
%{filter: filter, sort_field: field, sort_dir: dir,
page: page, per_page: per} = socket.assigns.table
{rows, total} = Accounts.list_users(
search: filter["search"],
status: filter["status"],
sort_field: field,
sort_dir: dir,
page: page,
per_page: per
)
socket
|> assign(:rows, rows)
|> assign(:table, DataTable.put_total(socket.assigns.table, total))
endHandle events
def handle_event("dt_filter", params, socket) do
table = socket.assigns.table
|> DataTable.set_filter(params)
|> DataTable.reset_page()
{:noreply, socket |> assign(:table, table) |> load_rows()}
end
def handle_event("dt_sort", %{"field" => field}, socket) do
table = DataTable.toggle_sort(socket.assigns.table, field)
{:noreply, socket |> assign(:table, table) |> load_rows()}
end
def handle_event("dt_paginate", %{"page" => page}, socket) do
table = DataTable.set_page(socket.assigns.table, String.to_integer(page))
{:noreply, socket |> assign(:table, table) |> load_rows()}
end
Summary
Functions
Returns the filter value for a given key.
True if any filter is active.
Create a new DataTable state struct.
Compute the SQL/Ecto offset for the current page.
Set total row count (used to compute total_pages).
Reset to page 1 (call after filter changes).
Update filter params. Strips blank values.
Set the current page.
Toggle sort on a field. Flips direction if already sorted by that field.
Compute total pages from total rows and per_page.
Types
@type t() :: %AvenUI.DataTable{ filter: map(), page: pos_integer(), per_page: pos_integer(), sort_dir: String.t(), sort_field: String.t() | nil, total: non_neg_integer() }
Functions
Returns the filter value for a given key.
True if any filter is active.
Create a new DataTable state struct.
Compute the SQL/Ecto offset for the current page.
Set total row count (used to compute total_pages).
Reset to page 1 (call after filter changes).
Update filter params. Strips blank values.
Set the current page.
Toggle sort on a field. Flips direction if already sorted by that field.
Compute total pages from total rows and per_page.