0

I am Vue developer for years ,

now I am trying to learn Reactjs and Nextjs.

and I am implementing user list page that include pagination ,

I have some problem with that

this is my code :

"use client";
import getUsers from "@/src/lib/service/user/GetUsers";
import { Avatar, Pagination } from "@mui/material";
import { useRouter } from "next/navigation";
import { useSearchParams } from "next/navigation";

import {
  QueryClient,
  QueryClientProvider,
  useQuery,
} from "@tanstack/react-query";
import { useState } from "react";

const queryClient = new QueryClient();

function UsersListInner() {
  const searchParams = useSearchParams();
  const router = useRouter();


  const [currentPage, setCurrentPage] = useState<number>(
    Number(searchParams.get("page") || 1)
  );

  const { data } = useQuery({
    queryKey: ["userList", currentPage],
    queryFn: () => getUsers({ page: currentPage }),
    staleTime: 0
    
  },);

  const handleChange = (event: React.ChangeEvent<unknown>, value: number) => {
    router.push(`?page=${value}`);
    setCurrentPage(value);
  };
  const totalPage = Math.ceil(
    (data?.pagination.total_count || 1) / (data?.pagination.item_per_page || 1)
  );

  return (
    <div>
      {data?.data.map((u) => (
        <div className="border-b p-4 flex gap-2 items-center" key={u.id}>
          <Avatar src="/images/person.svg" />
          <div>{u.fullName}</div>
          <div dir="ltr">{u.phone}</div>
        </div>
      ))}

      {data && (
        <Pagination
          page={currentPage}
          count={totalPage}
          onChange={handleChange}
        />
      )}
    </div>
  );
}

export default function UsersList() {
  return (
    <QueryClientProvider client={queryClient}>
      <UsersListInner />
    </QueryClientProvider>
  );
}

as you see this is client component

and I have used Tanstack for caching .

do you think what is the best practice for pagination in Next js ? or there is better approach ?

1 Answer 1

1

In NextJS you should fetch data in a server component then pass the data to client component, this is needed to reduce JavaScript on the client and improve performance, this is the whole idea of using NextJS, fetch data on server component and then send it to client component, a component that needs interactivity such as onClick or hooks needs to be a client component

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.