Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add parseAsPageIndex parser #791

Open
wants to merge 1 commit into
base: next
Choose a base branch
from
Open

Add parseAsPageIndex parser #791

wants to merge 1 commit into from

Conversation

cenobitedk
Copy link

Hi! Thanks for a great package!

I have suggestion for a (probably very) common use-case where you add the current page (eg. of a table) to the url. At least if you are doing pagination client-side. Typically you have the page as 0-index yet you want the url to be human readable starting from 1. Here parseAsPageIndex comes in super handy, taking care of the +1 offset automatically.

For example, let's say you use @tanstack/react-table and want to have the pagination as part of the url:

  const [pagination, setPagination] = useQueryStates(
    {
      pageIndex: parseAsPageIndex.withDefault(0),
      pageSize: parseAsInteger.withDefault(15),
    },
    {
      urlKeys: {
        pageIndex: 'page',
        pageSize: 'size',
      },
    },
  );

I was also thinking about parseAsIntegerWithOffset with any offset number, but I could only think of very few situations where it would be beneficial.

Copy link

vercel bot commented Dec 4, 2024

@cenobitedk is attempting to deploy a commit to the 47ng Team on Vercel.

A member of the Team first needs to authorize it.

@cenobitedk
Copy link
Author

The only challenge I've found is that setPagination returns a Promise which @tanstack/react-table doesn't like.
So it must be wrapped like this:

    onPaginationChange: (p) => {
      setPagination(p);
    },

Here's the full example:

  const [pagination, setPagination] = useQueryStates(
    {
      pageIndex: parseAsPageIndex.withDefault(0),
      pageSize: parseAsInteger.withDefault(15),
    },
    {
      urlKeys: {
        pageIndex: 'page',
        pageSize: 'size',
      },
    },
  );

  const table = useReactTable({
    columns,
    data,
    getCoreRowModel: getCoreRowModel(),
    getPaginationRowModel: getPaginationRowModel(),
    onPaginationChange: (p) => {
      setPagination(p);
    },
    state: {
      //...
      pagination,
    },
  });

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant