Next 13 tells me to gather input from client components and to fetch data from server components. If I want to fetch data based on the input from the client, how can I pass state from the client component to the server component.
-
Does this answer your question? [Update Server Component after data has changed by Client Component in Next.js](https://stackoverflow.com/questions/75124513/update-server-component-after-data-has-changed-by-client-component-in-next-js) – Youssouf Oumar Feb 02 '23 at 10:08
-
Not quite. That comments talks about updating the UI but I want to pass client information to a server component. – NaeNate May 07 '23 at 20:52
-
I don’t think you can do that. Server components are sent as HTML to the client, so there is no React concept for them, like passing props. – Youssouf Oumar May 07 '23 at 20:59
-
So whats my best option here. Fetch data from a client component? – NaeNate May 09 '23 at 21:29
4 Answers
The only opition is to pass the client data as a URL query using Router,
First, You push the data in the client component to the URL:
import { useRouter } from "next/navigation";
//You push when you get the data from the user (ex: OnSubmiting)
router.push(`URL?query=${something}`);
Second, You get the query in the server component:
const ServerComponent = (searchParams) => {
const something = searchParams.something
console.log(something) //You get your user data here
}
export default ServerComponen;

- 163
- 1
- 7
I think you can use SWR for this. https://swr.vercel.app/examples/ssr . SWR is built by developers of next js i presume, also in the above example you can see that the data from client is cached and passed to server.

- 118
- 5
If you are on the same page, fetch or SWR seems reasonable. If you are calling another page you can capture query arguments with searchParams.
In this case I'm passing ordernum from a client page to a server page. http://localhost:3000/test/serverpage?ordernum=456
interface PageProps {
params: Params;
searchParams: SearchParams;
}
interface Params {
slug: string;
}
interface SearchParams {
[key: string]: string | string[] | undefined;
}
export default async function Page({ searchParams }: PageProps) {
console.log("order num", searchParams.ordernum);
return (
<div className="flex flex-col items-center justify-center h-screen">
<h1 className="text-2xl font-bold mb-4">Order Number: {searchParams.ordernum}</h1>
</div>
);
};

- 360
- 1
- 3
- 14
You cannot share stated between ssr
and csr
, as some solutions suggests you could use queries but overall you'll have to use HTTP requests to handle the data sharing between your server side and client side which involves creating a API endpoint.

- 929
- 5
- 15