can i fetch data in a layout component? im getting this error
Unanswered
American Robin posted this in #help-forum
American RobinOP
Unhandled Runtime Error
Error: connect ECONNREFUSED ::1:80
Error: connect ECONNREFUSED ::1:80
20 Replies
American RobinOP
const response = await axios.get("/api/language");
console.log(response);import { NextRequest, NextResponse } from "next/server";
export async function GET(req: NextRequest) {
return NextResponse.json({
message: "Hello World",
});
}nothing special so far
You can’t fetch own API endpoints in server components, just invoke the function directly
That’s because route handlers aren’t available at the moment of build pages, so requests will be failed
That’s because route handlers aren’t available at the moment of build pages, so requests will be failed
American RobinOP
uhm
so i have to create a function
and use it in the layout.tsx?
Yea, like invoking
getPosts directlyAmerican RobinOP
oke ill try that
mhm smth still not workin properly
What do you mean by not working?
American RobinOP
i get the same error
Impossible unless you misunderstood what I mean, since you’re not using
fetch anymoreAmerican RobinOP
still new to api calls etc :(( tryin
wait i can show
what i did
in the layout.tsx:
const getLanguage = async () => {
const response = await axios.get("/api/language");
console.log(response);
};
const test = await getLanguage();
console.log(test);As above mentioned:
1. Don’t fetch own api endpoints from server components
2. Axio is no longer recommended, just use the native fetch API
1. Don’t fetch own api endpoints from server components
2. Axio is no longer recommended, just use the native fetch API
Here’s a detailed answer
https://nextjs-discord-common-questions.joulev.dev/fetching-own-api-endpoint-in-react-server-components
https://nextjs-discord-common-questions.joulev.dev/fetching-own-api-endpoint-in-react-server-components