Listing Context
ListingContext is the central state manager for all CRUD listing pages. It manages API data fetching, pagination, sorting, filter state, and URL query string synchronization.
Import
import { ListingContext } from "@phpcreation/frontend-crud-react-nextjs-bundle/contexts/ListingContext";What It Manages
| State | Description |
|---|---|
data | Current page of entities from the API |
total | Total entity count |
page | Current page number |
perPage | Page size |
sort | Sort column and direction |
filters | Active filter values |
loading | Loading state |
error | Error state |
Reordering handlers
Row reordering lives in this context, used by the ListingActions move buttons:
| Handler | What it does |
|---|---|
handleMoveItem(id, direction, neighborId) | Swaps the priority values of the row and its adjacent row (two PATCH requests), then swaps them in local state. |
handleTreeMoveItem(id, direction) | Swaps lft/rgt with the adjacent same-parent sibling (two PATCH requests), then refetches. Used on the tree view route. |
moveLoadingIds / treeMoveLoadingIds | Ids with an in-flight move, used to show the button spinners. |
Usage
Wrap all listing components in ListingContext:
import { ListingContext } from "...";
import { ListingTable } from "...";
import { ListingFilters } from "...";
import { ListingPagination } from "...";
<ListingContext entityConfig={entityConfig}>
<ListingFilters filterFields={filterFields} />
<ListingTable columns={columns} actions={actions} />
<ListingPagination />
</ListingContext>useListingContext Hook
Access context state in child components:
import { useListingContext } from "@phpcreation/frontend-crud-react-nextjs-bundle/contexts/ListingContext";
function MyComponent() {
const { data, loading, setFilters, setPage } = useListingContext();
// ...
}Entity Config
Pass your entity’s API config to the context:
export const entityConfig = {
apiUrl: "/api/invoices",
defaultSort: { field: "createdAt", direction: "desc" },
defaultPerPage: 25,
};ListingContext syncs all state to the URL query string automatically via the Query String module. No extra setup is needed.
Related
Last updated on