Next.js Discord

Discord Forum

The Loading.tsx does not behave as expected.

Unanswered
Giant Angora posted this in #help-forum
Open in Discord
Avatar
Giant AngoraOP
I'm encountering a situation with Loading.tsx where there are no compile or runtime errors, but it does not behave as expected.

Expected Behavior:
When the user updates the searchParams, the Loading.tsx should display the message "Loading..." each time the searchParams change.

Actual Behavior:
The loading message from Loading.tsx only appears during the initial request (when I visit the page directly via URL or using <Link />). It does not show when searchParams are updated afterward.

/search/layout.tsx
export default function Layout(props: LayoutProps) {
  const { children } = props;

  return (
    <main className="p-5">
      <header aria-label="search glasses">
        <React.Suspense>
          <SearchForm />
        </React.Suspense>
      </header>

      {children}
    </main>
  );
}


/search/page.tsx
export default async function SearchPage(props: SearchPageProps) {
  const searchParams = await props.searchParams;

  // TODO: implement db logic

  const data = await new Promise((resolve) =>
    setTimeout(() => resolve(searchParams), 1000),
  );

  return <section>{JSON.stringify(data, null, 2)}</section>;
}

1 Reply

Avatar
Giant AngoraOP
SearchForm
export const SearchForm = () => {
  const nameId = React.useId();

  const searchParams = useSearchParams();

  const name = searchParams.get('name') || '';

  return (
    <Form action="" className="mx-auto w-full max-w-md">
      <search className="grid grid-cols-1 gap-3 md:grid-cols-2 lg:grid-cols-1">
        <div className="space-y-1 md:col-span-2 lg:col-span-1">
          <Label htmlFor={nameId}>Name</Label>
          <Input
            name="name"
            defaultValue={name}
            id={nameId}
            className=""
          />
        </div>
      </search>

      <div className="mt-3 flex flex-col items-start gap-2 @xs:flex-row @xs:items-center">
        <div className="ml-auto shrink-0">
          <Button type="reset" variant="ghost" className="mr-2">
            Reset
          </Button>

          <Button type="submit">Search</Button>
        </div>
      </div>
    </Form>
  );
};