Next.js Discord

Discord Forum

Re-activate Suspense upon query param change on app dir

Unanswered
American Wirehair posted this in #help-forum
Open in Discord
American WirehairOP
I have a page where the query params are passed into a server component that fetches data and passes it to a client table component. I wrap my data-fetching component in a Suspense block to stream it and to display the rest of the UI while the data is fetched. My search box runs router.push to /search?q=${query} when the search button is pressed. When this is done from /, the surrounding UI instantly appears and the Suspense loading message displays before the table loads in. However, subsequent searches from the /search page doesn't trigger the Suspense and instead blocks all UI until the data is fetched and the data loads in. How can I make it so navigations from /search?q=query1 to /search?q=query2 re-triggers Suspense and streams the data table?

3 Replies

American WirehairOP
search/page.tsx:
export default async function Search({
  searchParams,
}: {
  searchParams: { q?: string };
}) {
  const safeQuery = searchSchema.safeParse(searchParams.q ?? "");
  return (
    <div className="flex min-h-screen flex-col items-center md:w-4xl sm:w-2xl w-full">
      <main>
        <h1 className="text-4xl tracking-tighter my-4 mx-2">
          Search over <b>100,000+</b> American small businesses
        </h1>
        {safeQuery.success && (
          <Suspense
            fallback={
              <SearchBox
                defaultValues={{ query: searchParams.q ?? "" }}
                disabled={true}
              />
            }
          >
            <SearchBox
              defaultValues={{ query: searchParams.q ?? "" }}
              disabled={false}
            />
            <div className="mt-4 sm:w-full w-screen overflow-y-scroll">
              <QueryTable q={safeQuery.data} key={safeQuery.data}/>
            </div>
          </Suspense>
        )}
      </main>
    </div>
  );
@joulev you can add `key` like ts <Suspense key={query}> ... </Suspense>
American WirehairOP
Amazing, thank you!