Reputation: 47
I'm trying to fetch data from an external API in a server component which is considered good practice but in this scenario my GET request depends on a variable called menu_id
(inside child.tsx) and will fetch different data depending on the value.
i also use zustand as my state manager but i can't get access to it in server components
parent.tsx(server component):
const getMenuData = async (menu_id: number) => {
const res = await fetch(`${menu_id}/items/}/items/`);
return res.json();
};
export default async function DashboardLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<div className="flex h-screen flex-col bg-primary">
<ChildComponent></ChildComponent>
</div>
);
}
child.tsx(client component):
export default function ChildComponent({
name,
position,
places,
}: MyPlacesTabType) {
const [IsOpen, setIsOpen] = useState(false);
const [currentMenu, setCurrentMenu] = useState("venhan");
const tab = useRef(null);
const handleClick = (menu_id: string) => {
setIsOpen((prev) => !prev);
setCurrentMenu(menu_id);
//the GET request in parent.tsx depends on menu_id here
};
return (
<div
ref={tab}
>
<section>
{places.map((place) => (
<Button
onClick={handleClick}
>
{place.name}
</Button>
))}
</section>
</div>
);
}
what is the right way of providing menu_id
to this server component?
Upvotes: 1
Views: 338
Reputation: 624
The normal way to handle this for things that don't rely on user interaction is to use a cookie which can then be retrieved on the server. Since yours is attached to a click event, it's unreasonable to make a request to the server, set the cookie, wait for a refresh and then use the cookie to run something on the server.
If you really want to streamline this, look into TRPC and setting up both a server and client side client. With that you can write the method once and just import it from a different location depending on whether you want to run it on the server or the client, otherwise you just have to write the query on the client.
The whole 'run your queries in server components' methodology only holds true if the query is something you're running immediately on render where previous approaches involved just putting it in a useEffect
hook after the client component renders. Queries that run literally any time after that need to be pushed down to the client (or a server action).
Upvotes: 0