Next.js Discord

Discord Forum

How to fetch data from a component

Unanswered
Pembroke Welsh Corgi posted this in #help-forum
Open in Discord
Pembroke Welsh CorgiOP
Hi! I'm working on a school assignment where I need to build a webshop. I’m stuck on the part where I need to fetch the data. I’ve created two components: one to display all products and one for individual product details. I’m trying to retrieve the product data through an API, but when I run the code, I’m getting a "fetch failed" error.
Can anyone help me figure out what might be going wrong? https://github.com/CristianM100/modules.shop/tree/main

9 Replies

New Guinea Freshwater Crocodile
Hey,
1. unless intended you should not have pages under api dir, but [routes](https://nextjs.org/docs/pages/building-your-application/routing/api-routes).
2. The route should return data, but yours returning component.
3. However on [this line](https://github.com/CristianM100/modules.shop/blob/1d6e9bae403899ba13362ef2fd016af0f328c2d9/app/api/products/page.tsx#L21) you have a circular call to itself, so it can't even work.
at: app/products/page.tsx

const fetchProducts = async (page: number): Promise<{ results: ProductType[] }> => { // call the database, third party API via fetch, whatever.. const products = await yourFetchingLogicHere(); return products; }; const Page = async () => { const products = await fetchProducts(); return <Products products={products} />; }; export default Page;
And you would do the same with the GetById scenario. You don't need to spin up an API Route Handler with React Server Components, unless you need to fetch data from the client and you can't pass that data down from a Server parent component to its children.
You’re still hitting the same route handler, did you fix it?

Something we noticed in your previous code from the repo was that you were exporting components from inside the app/api folder
Pembroke Welsh CorgiOP
I deleted app/api/products/ and I thought that is possible to fetch the data from the component in app/products/page.tsx
I dont know how to fix the route handler
I guess i need to review the documentation
@Pembroke Welsh Corgi I guess i need to review the documentation
Yes that a should’ve been the first thing to do.

Maybe you don’t even need a route handler if you can move that logic to the function that’s called directly into the React Server Component