TypeError: fetch failed
Answered
Baltimore Oriole posted this in #help-forum
Baltimore OrioleOP
getting this error while doing revalidatePath in a server component. I'm adding headers from next/headers in the api request. The response is coming fine for the first time but it's failing on revalidatePath. Need help.
Thanks
Thanks
20 Replies
@Ray could you show the code?
Baltimore OrioleOP
export async function GET(request: NextRequest) {
const session = await getServerSession(authOptions);
if (!session) {
return new Response("not logged in");
}
const comments = await db.comment.findMany({
include: {
user: true,
},
});
return new Response(JSON.stringify(comments));
}this is the endpoint
async function addComment(formData: FormData) {
"use server";
await db.comment.create({
data: {
comment: formData.get("comment") as string,
postedOn: new Date(),
user: {
connect: {
id: "65b2c603bfed17c98012bf4e", // Replace with the actual User ID
},
},
},
});
revalidatePath("/dashboard");
}
return (
<>
<div className="min-h-screen pt-10 px-20">
<h1>This is DashBoard for {session.user.email}</h1>
<div>
<form action={addComment}>
<input type="text" name="comment" />
<button type="submit">Submit</button>
</form>
</div>
<CommentList />
</div>
</>
);
}this is the server component which is importing another server component
import { headers } from "next/headers";
async function getComments() {
try {
const res = await fetch("http://localhost:8080/api/posts", {
method: "GET",
headers: headers(),
next: {
tags: ["comment-data"],
},
});
const comments: {
id: string;
comment: string;
userId: string;
postedOn: Date;
}[] = await res.json();
return comments;
} catch (e) {
console.log(e);
}
}
export default async function CommentList() {
const comments = await getComments();
return (
<div>
{comments?.map((c) => (
<li key={c.id}>{c.comment}</li>
))}
</div>
);
}this is Comment-List
Baltimore OrioleOP
yes
@Baltimore Oriole just updated this
http://localhost:8080/api/posts is the GET endpoint above?Baltimore OrioleOP
yes
its working on first render
@Baltimore Oriole its working on first render
you should move the work from the GET endpoint to
getComments() insteadBaltimore OrioleOP
work?
the code
the query
Baltimore OrioleOP
ok got it
use
unstable_cache if you want to tag itBaltimore OrioleOP
is there any other way to fix this. I don't want to move the endpoint
you shouldn't fetch self api in server component
Answer
you could leave the endpoint if you need it outside of the web but change the code in
getComments()Baltimore OrioleOP
ok . Thanks @Ray