Next.js Discord

Discord Forum

Help Fetch Data E-commerce API

Answered
Cinnamon Hummingbird posted this in #help-forum
Open in Discord
Cinnamon HummingbirdOP
I want to fetch order data from our E-commerce store so I can make a sales graph that shows the amount of sales per hour.

Through console logging I know that the route.js file works & returns the correct data via
return NextResponse.json(allSales, { status: 200 });
in the api directory.

In a utils directory I try to access this data in a processData.js file, With this as the first few lines of code;
"use client";

export const calculateHourlyRevenue = (invoiceRequests) => {
    const hourlyRevenue = {};
    const today = new Date().toISOString().split('T')[0]; // Gets today's date as YYYY-MM-DD in UTC

    console.log("Expected today's date:", today);
    console.log("Total invoice requests:", invoiceRequests.length);

With this as output for the console log:

processData.js:7 Expected today's date: 2024-04-25
processData.js:8 Total invoice requests: 0
processData.js:34 Hourly revenue calculated: {}

I'm not sure how to fix this issue. How can I access the data that I got via the route.js file?
Answered by American Crow
You'd have to fetch your own route handler in your client component.
Your endpoint is at /api/[Name off Folder your route.ts is in]

Another (maybe better solution) would be to use a server component and fetch your E-Commerce endpoint directly from there const data = await fetch(www.yourecomerce/stats and pass data down to your client component. That way you would not need a route.ts at all
View full answer

2 Replies

American Crow
You'd have to fetch your own route handler in your client component.
Your endpoint is at /api/[Name off Folder your route.ts is in]

Another (maybe better solution) would be to use a server component and fetch your E-Commerce endpoint directly from there const data = await fetch(www.yourecomerce/stats and pass data down to your client component. That way you would not need a route.ts at all
Answer