Skip to content

Commit

Permalink
fix index pagination
Browse files Browse the repository at this point in the history
  • Loading branch information
eaguad1337 committed Oct 22, 2023
1 parent 31ff358 commit 5e9a988
Show file tree
Hide file tree
Showing 6 changed files with 77 additions and 16 deletions.
8 changes: 4 additions & 4 deletions src/collapsar/Resource.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,9 @@ def fields(cls):
@classmethod
def paginate(cls, collapsar_request: "CollapsarRequest"):
"""Paginate the resource."""
paginator = cls.model.paginate(collapsar_request.param("per_page", 10))
paginator = cls.model.paginate(
collapsar_request.input("per_page", 10), int(collapsar_request.input("page", 1))
)

def _resolve_fields(model, resource: "Resource"):
return (
Expand All @@ -49,9 +51,7 @@ def _resolve_fields(model, resource: "Resource"):

paginator = paginator.serialize()
paginator["data"] = data
paginator["fields"] = [
field for field in data[0]
] if len(data) > 0 else []
paginator["fields"] = [field for field in data[0]] if len(data) > 0 else []

return paginator

Expand Down
42 changes: 31 additions & 11 deletions src/collapsar/assets/js/pages/ResourceIndex.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,31 +32,39 @@ import {
TableHeader,
TableRow,
} from "@/components/ui/table";
import { Link, useNavigate, useParams } from "react-router-dom";
import { Link, useNavigate, useParams, useSearchParams } from "react-router-dom";

import { ResourceIndexRowActions } from "@/components/ResourceIndexRowActions";

export function ResourceIndex() {
const { resource } = useParams();

const [data, setData] = React.useState([]);
const [meta, setMeta] = React.useState({} as any);
const [fields, setFields] = React.useState([]);
const [sorting, setSorting] = React.useState<SortingState>([]);
const [searchParams, setSearchParams] = useSearchParams()

const [pagination, setPagination] = React.useState({
pageIndex: searchParams.has('page') ? parseInt(searchParams.get('page')) : 1,
pageSize: 10,
});
const [columnFilters, setColumnFilters] = React.useState<ColumnFiltersState>(
[]
);
const [columnVisibility, setColumnVisibility] =
React.useState<VisibilityState>({});
const [rowSelection, setRowSelection] = React.useState({});

React.useEffect(() => {
axios
.get(`/collapsar/api/${resource}?displayForIndex=true`)
.then((response) => {
setData(response.data.data);
setFields(response.data.fields);
});
}, [resource]);
const handlePagination = ({ page }) => {
axios.get(`/collapsar/api/${resource}?page=${page}`).then((response) => {
setData(response.data.data);
setFields(response.data.fields);
setMeta(response.data.meta);

setSearchParams(`?${new URLSearchParams({ page: response.data.meta.current_page })}`)
});
};

const constructColumns = (fields: any[]): ColumnDef[any] => {
const columns = fields.map((field, k) => {
Expand Down Expand Up @@ -133,6 +141,9 @@ export function ResourceIndex() {
const table = useReactTable({
data: data,
columns,
manualPagination: true,
onPaginationChange: setPagination,
pageCount: meta.last_page,
onSortingChange: setSorting,
onColumnFiltersChange: setColumnFilters,
getCoreRowModel: getCoreRowModel(),
Expand All @@ -146,16 +157,21 @@ export function ResourceIndex() {
columnFilters,
columnVisibility,
rowSelection,
pagination,
},
});

React.useEffect(() => {
handlePagination({ page: table.getState().pagination.pageIndex });
}, [resource, pagination]);

return (
<div className="w-full">
<h1>Resources</h1>

<div className="flex items-center py-4">
<Input
placeholder="Filter emails..."
placeholder="Search records"
value={(table.getColumn("email")?.getFilterValue() as string) ?? ""}
onChange={(event) =>
table.getColumn("email")?.setFilterValue(event.target.value)
Expand Down Expand Up @@ -251,12 +267,16 @@ export function ResourceIndex() {
{table.getFilteredSelectedRowModel().rows.length} of{" "}
{table.getFilteredRowModel().rows.length} row(s) selected.
</div>

<div className="flex-1 text-sm text-muted-foreground">
Page {table.getState().pagination.pageIndex} of{" "} {meta.last_page}
</div>
<div className="space-x-2">
<Button
variant="outline"
size="sm"
onClick={() => table.previousPage()}
disabled={!table.getCanPreviousPage()}
disabled={table.getState().pagination.pageIndex <= 1}
>
Previous
</Button>
Expand Down
10 changes: 10 additions & 0 deletions tests/integrations/config/factories.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# config/factories.py
from masoniteorm import Factory
from tests.integrations.app.models.Article import Article


def article_factory(faker):
return {"title": faker.text(), "content": faker.text(), "user_id": None}


Factory.register(Article, article_factory)
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ def up(self):
with self.schema.create("articles") as table:
table.uuid("id").primary()
table.string("title")
table.unsigned_big_integer("user_id")
table.unsigned_big_integer("user_id").nullable()
table.text("content")
table.timestamps()

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
"""TestMigrationNotMigrated Migration."""

from masoniteorm.migrations import Migration


class TestMigrationNotMigrated(Migration):
def up(self):
"""
Run the migrations.
"""
with self.schema.create("test_migration_not_migrateds") as table:
table.increments("id")

table.timestamps()

def down(self):
"""
Revert the migrations.
"""
self.schema.drop("test_migration_not_migrateds")
11 changes: 11 additions & 0 deletions tests/integrations/databases/seeds/article_table_seeder.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
"""ArticleTableSeeder Seeder."""

from masoniteorm.seeds import Seeder
from masoniteorm import Factory
from tests.integrations.app.models.Article import Article


class ArticleTableSeeder(Seeder):
def run(self):
"""Run the database seeds."""
Factory(Article, 50).create()

0 comments on commit 5e9a988

Please sign in to comment.