2

I am trying to wrap my head around the best Next.js 13 folder structure under app/ to generate the following search flow:

  • The user visits /search and enters a search query in the search box at the top
  • The URL changes to /search?q=my+query
  • The section under the search box has a split view, showing:
    • on the left, a long list of search results, implementing pagination with infinite scrolling; the first result is selected by default (UI-wise it is highlighted somehow)
    • on the right, the details of the selected search result are shown; the URL could change to reflect the selected result, e.g. /search/result-slug?q=my+query

Since pagination is a client concern, I understand that I'll need to use a client-fetching library like SWR. However, ideally, I'd like the first results to be rendered by the server (i.e. the first results page shown on the left sidebar, the first item on that list highlighted, and its details shown on the right).

I tried to follow the code in app playground, but the approach doesn't seem to work here. Layouts don't accept search parameters, and these are needed in this case - unlike that repo where the "results" (categories) rendered in the layout are yielded by the same API call. Rendering a client component from the layout and using useSearchParams means I won't be able to fetch the first page from the server using the promise pattern.

So it seems like I need to pull the list on the left sidebar via a page rather than a layout, but then I am not sure how to make this properly interact with the content area on the right. So while in my mind this use-case calls for composability, I'm not sure how to best implement it in the folder structure.

Is there an idiomatic solution here that does not require ditching server-side rendering all together?

AmitA
  • 3,239
  • 1
  • 22
  • 31
  • In the page /search you have access to the `searchParams` object. Doc: https://beta.nextjs.org/docs/api-reference/file-conventions/page. Also, check this thread: https://stackoverflow.com/a/74983731/7982963 – Moaaz Bhnas Apr 23 '23 at 15:29
  • Yes, I'm aware of `searchParams`, however it's on the page level only, so I cannot have the layout handle and render the list of search results and wrap a leaf level page that shows the description (like they do in the app playground). – AmitA Apr 23 '23 at 17:06

1 Answers1

0

I ended up with a single page under app/search/page.js as layouts do not seem to offer an advantage here.

page.js fetches from the DB the first page of search results and the details of the first search result. It serializes these and sends the information across the wire to a client component that shows the split view.

The client component loads its cache with the initial data from the server and shows the information immediately. It performs API calls to fetch additional information when needed.

AmitA
  • 3,239
  • 1
  • 22
  • 31