Client side fetching
Answered
Munchkin posted this in #help-forum
MunchkinOP
Hello, I am trying to fetch and post data by making http request. However when I add the call to the client component and I test it, it keeps rebuilding the component and making request every second.
This is the component:
The only recourse I found is this: https://nextjs.org/docs/pages/building-your-application/data-fetching/client-side. However that's for pages router and I use app router.
What should I do to fix this behaviour?
This is the component:
"use client";
import { fetchData } from "@/libs/utils";
export default async function Template({ params }: { params: { id: string } }) {
const url = "/api/my_template/" + params.id;
let api_result = undefined;
try {
api_result = await fetchData(url);
} catch (e) {
return <>Something went wrong</>;
}
console.log("api result:", api_result);
return <></>;The only recourse I found is this: https://nextjs.org/docs/pages/building-your-application/data-fetching/client-side. However that's for pages router and I use app router.
What should I do to fix this behaviour?
13 Replies
European sprat
Client components can't be async
@European sprat Client components can't be async
MunchkinOP
How do I fetch data then?
Use something other than fetch function?
European sprat
Based on your example, it doesn't look like you need it to be a client component
MunchkinOP
well, yeah. Im planning to separate it later
but Im gonna do post request when user clicks button
European sprat
Well then you'd make the onClick handler inside the component an async function and call the fetch in there
MunchkinOP
I thought I cant use onClick in server component
@Munchkin but Im gonna do post request when user clicks button
European sprat
This implies client component
MunchkinOP
I also tried to pass function that I would use in onClick from server to client component but thats not possible afaik
European sprat
I suggest reading this page and referencing it. It should help figure out how to get started
MunchkinOP
hmm, okay
Answer