How to update and display server-side data in a table with pagination using useActionState in Next.js?

I am using useActionState to trigger a server-side action fetchPeople for form submission. Outside of the form, there is a table with pagination where I display the data returned from the server.

I am trying to update serverState by passing an additional prop (page) to trigger the fetch API again, change the current page, and return new people from that page.

I have successfully done that by clicking on a new page from the pagination below the table… I can see that the pagination and people object from the response has changed, but I have an issue with sending that updated response to the client.

Where am I making a mistake that prevents me from sending the updated data to the client and displaying it in the table?

StepOneForm.tsx

"use client"

export default function StepOneForm() {
  const [serverState, formAction, isPending] = useActionState(fetchPeople, {});
  const formRef = useRef<HTMLFormElement | null>(null);

  const totalPages = serverState.pagination?.total_pages ?? 0;
  const currentPage = serverState.pagination?.page || 1;
  const totalEntries = serverState.pagination?.total_entries;

  const pagination = getPages({ totalPages, currentPage });

  async function handlePageChange(page: number) {
    if (formRef.current) {
      const formData = new FormData(formRef.current);

      fetchPeople(serverState, formData, page);
    }
  }

  const handleSubmit = async (event: React.FormEvent) => {
    event.preventDefault();
    const formData = new FormData(event.target as HTMLFormElement);

    startTransition(() => {
      formAction(formData);
    });
  };

  return (
    <>
      <div className="grid grid-row sm:grid-cols-2 gap-5 mt-7">
        <form
          onSubmit={handleSubmit}
          ref={formRef}
          className="order-2 sm:order-1"
        >
          <!-- not relevant code -->
        </form>

        <!-- table with data returned from server side action -->
        <div className="grid grid-cols-1 md:grid-cols-3 mt-3">
          {serverState.people.map((contact: any) => {

          return (
            ...
          );
        })}
      </div>

      <!-- table pagination -->
      <div className="flex items-center justify-between border-t border-gray-200 bg-white py-3">
            <nav
              aria-label="Pagination"
              className="isolate inline-flex -space-x-px rounded-md shadow-sm"
            >
              {pagination.map((page, index) =>
                page === "..." ? (
                  <span
                    key={`ellipsis-${index}`}
                    className="relative inline-flex items-center px-4 py-2 text-sm font-semibold text-gray-500"
                  >
                    ...
                  </span>
                ) : (
                  <Link
                    href=""
                    key={page}
                    className={`cursor-pointer relative inline-flex items-center px-4 py-2 text-sm font-semibold ${
                      page === currentPage
                        ? "z-10 bg-indigo-600 text-white focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600"
                        : "text-gray-900 ring-1 ring-inset ring-gray-300 hover:bg-gray-50 focus:outline-offset-0"
                    }`}
                    onClick={async (e) => {
                      e.preventDefault();
                      await handlePageChange(+page);
                    }}
                  >
                    {page}
                  </Link>
                )
              )}
            </nav>
        </div>
      </div>

actions/people.ts

"use server"

export async function fetchPeople(
  prevState: any,
  formData: FormData,
  page: number = 1
): Promise<any> {
  try {
    const validated = stepOneSchema.safeParse({
      name: formData.get("name"),
      company: formData.get("company"),
      web: formData.get("web"),
      country: formData.get("country"),
    });

    if (!validated.success) {
      return {
        errors: validated.error.flatten().fieldErrors,
      };
    }

    const baseUrl = `https://api.apollo.io/api/v1/mixed_people/search`;
    const params = new URLSearchParams();

    const { name, company, web, country } = validated.data;

    if (country) params.append("organization_locations[]", country);
    if (name) params.append("q_keywords", name);
    if (company) params.append("q_keywords", company);
    if (web) params.append("q_organization_domains[]", web);

    const url = `${baseUrl}?${params.toString()}&page=${page}&per_page=10`;

    const response = await fetch(url, {
      method: "POST",
      headers: {
        accept: "application/json",
        "Cache-Control": "no-cache",
        "Content-Type": "application/json",
        "x-api-key": process.env.APOLLO_API_KEY as string,
      },
    });

    const peopleData = await response.json();

    if (!response.ok) {
      throw new Error(`Apollo API error: ${peopleData.message}`);
    }

    const people = peopleData.people.map((person: any) => ({
      name: person.name,
      title: person.title,
      company: person.organization.name,
    }));

    const pagination = peopleData.pagination;

    console.log('server side response', pagination, people);

    return { success: true, people, pagination };
  } catch (error: any) {
    console.error(error);
  }
}

2

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật