I’m building a Next.js app and running into an issue where my frontend component gets an empty object when calling my API route, even though the API is returning data correctly.
Backend API Route
My API route at pages/api/orders/index.js fetches data from database:
import { db } from "@/utils/database";
export default async function handler(req, res) {
if (req.method === 'GET') {
const ordersList = await db.orders.findAll();
console.log("Database orders:", JSON.stringify(ordersList));
return res.status(200).json(ordersList);
}
}
The backend logs show data is retrieved successfully:
Database orders: [{"order_id":10,"created_at":"2024-09-12T08:15:30.123Z","customer_table":5,"item":"Coffee","completed":true}]
Frontend Component Issue
But when I call this API from my component:
"use client";
import { useState, useEffect } from 'react';
const OrderManager = () => {
const [orders, setOrders] = useState([]);
const fetchOrders = async () => {
const response = await fetch('/api/orders');
console.log("API response:", JSON.stringify(response));
};
useEffect(() => {
fetchOrders();
}, []);
return (
<div>
{/* Component JSX */}
</div>
);
};
export default OrderManager;
The console shows an empty object instead of the actual data. What am I missing here? The API works fine but the frontend isn’t getting the right data.