0

I've put together a Client and a Server component (based on App Router), and managed to refresh Server on user input (specifically when the user types anything), basically forcing a refresh of the route.-

router.push(pathname)

So far so good, but I actually need to pass user input from Client to Server in order to filter fetch based on it (i.e a date range).

I'm guessing I could use dynamic routes, but semantically doesn't feel right (it's not like I'm navigating to an entity detail). Also, server actions kind of looks what I need, but since it's an experimental feature, I was wondering if there's already a different approach available; Server fetch based on user input seems like a basic feature to me, but still can't find a straight "official" pattern to get it working.

Any alternatives / suggestions?

EDIT As @ivanatias suggested, this thread shows how to pass params through query strings, while this could potentially work, unfortunately since the url is changing, the state of the input fields is lost.

ssantos
  • 16,001
  • 7
  • 50
  • 70
  • So, this input is rendered on this page server component and on user input, you want to apply certain filters so data can be fetched based on these on the server component (same route, different data) right? If so, maybe [this](https://stackoverflow.com/questions/75839736/using-state-in-server-components-next13/75840354#75840354) can help you. – ivanatias May 17 '23 at 19:09
  • Thank you @ivanatias, the input itself is in the client component, but yep, that thread looks very promising! Just wondering how these searchParams are not mentioned in the Routing Fundamentals :) Thanks again. – ssantos May 17 '23 at 19:15

1 Answers1

2

You can use updating searchParams example in Next.js 13 doc (app Dir).

  • the idea is to use a combination of client hooks ( usePathname, useSearchParams, and useRouter) where imports from next/navigation.
Saheb Mohammadi
  • 406
  • 3
  • 5
  • Thank you, wasn't aware of the example but it's pretty clear. The only issue I still had is that I was losing the state, but finally I'm using useSearchParams in the client itself to restore the corresponding vars on redirect. – ssantos May 17 '23 at 20:04
  • 1
    for the search state, You can get the query parameter from URL (using the above hooks) and update the search state based on the useEffect. Remaining states can be stored in localStorage or refetch states based on the app scenario from the backend. – Saheb Mohammadi May 17 '23 at 21:22