Reputation: 295
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.
Server Actions have fixed this issue.
Upvotes: 8
Views: 6348
Reputation: 1087
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.
Upvotes: 0
Reputation: 390
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>
);
};
Upvotes: 0
Reputation: 319
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;
Upvotes: 3
Reputation: 116
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.
Upvotes: 0