NextJS基于客户输入的服务器获取

huangapple go评论66阅读模式
英文:

NextJS server fetch based on client input

问题

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.

英文:

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.

答案1

得分: 3

你可以使用更新 searchParams 的方法,在 Next.js 13 文档的示例中(app 目录)。

  • 这个想法是使用客户端钩子的组合(usePathnameuseSearchParamsuseRouter),这些钩子从 next/navigation 中导入。

英文:

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.

huangapple
  • 本文由 发表于 2023年5月18日 03:02:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/76275417.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定