Strategies for transferring Next.js backend data to the frontend?

I've encountered an issue while working with Next.js. In a simple code setup, the frontend component is making a call to the backend endpoint. The backend successfully retrieves the data from the database, but the frontend consistently receives an empty object.

Here's the backend API endpoint responsible for fetching data:

File:

src/app/api/clientOrders/route.ts
:

import { prisma } from "@/lib/prisma";

...

export async function GET(request: NextRequest) {
    const clientOrders = await prisma.clientOrders.findMany();

    console.log("--> clientOrders = " + JSON.stringify(clientOrders));

    return NextResponse.json(clientOrders);
}

The backend logic seems to be functioning correctly as it successfully displays the retrieved DB records:

--> clientOrders = [{"id":1,"request_time":"2024-09-11T10:04:05.209Z","done_time":"2024-09-11T10:04:05.209Z","table_number":1,"order":"Arrived","status":false,"done_by":"-"}, ...]

The problem arises on the front-end side now. File:

src/components/RestaurantActions/index.tsx
:

"use client";
import { prisma } from "@/lib/prisma";
import Image from 'next/image';

const RestaurantActions = () => {

    async function getClientOrders() {        
        const clientOrdersData = await fetch('http://localhost:3000' + '/api/clientOrders', {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
            },
        });

        console.log("=> ClientOrders retrieved stringified = " + JSON.stringify(clientOrdersData));
        
    }

    getClientOrders()

    return(
        // The component's HTML
    )
}

export default RestaurantActions

Even though the frontend component triggers the backend API call, the data displayed in the console.log() always shows an empty object {}.

index.tsx:29 => ClientOrders retrieved from the backend = {}

Any insights on why the frontend isn't receiving the data fetched from the database?

Answer №1

To begin, make sure to convert the response to JSON format

async function fetchClientOrders() {
  const clientOrdersData = await fetch(
    'http://localhost:3000' + '/api/clientOrders',
    {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
      },
    }
  );
  //Include this additional line
  const clientOrdersJSON = await clientOrdersData.json();
  //
  console.log(
    '=> ClientOrders data retrieved in string format = ' +
      JSON.stringify(clientOrdersJSON)
  );

  return clientOrdersJSON;
}

View a functioning example here

Answer №2

To execute the function, use this syntax:

const dataFetch = await (await fetch('http://localhost:3000/api/data')).json();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using Swig's conditional extend tag with Express.js and Node.js to leverage dynamic content rendering

Is there a way to make the extend tag for the Swig templating engine conditional or able to use a passed variable? Instead of using this code: {% extends '../layouts/layout.view' %} I would prefer to do something like this: {% extends layout ...

Vue messaging application fails to display data upon mounting

Recently, I've been experimenting with different Vue chat libraries and encountered this interesting piece of code: <template> <p>{{ this.users[0] }}</p> </template> <script> export default { data() { return ...

A guide on merging existing data with fresh data in React and showcasing it simultaneously

As a newcomer to Reactjs, I am facing the following issue: I am trying to fetch and display new data as I scroll down Every time I scroll down, I fetch the data and save it in Redux. However, due to pagination, only 10 items are shown and not added to th ...

The onClick event is not functioning properly with React's select and option elements

Looking for a way to get the option value from each region? const region = ['Africa','America','Asia','Europe','Oceania']; <div className="options"> <select> ...

Guide to utilizing exact matching functionality in ExpressJs router

In my ExpressJs application, I have defined two routes like so: router.get("/task/", Controller.retrieveAll); router.get("/task/seed/", Controller.seed); When I make a request to /task/seed/, the Controller.retrieveAll function is call ...

Display the image regardless of whether the component is currently visible

I need help with my Vue.js web application that includes a side navigation menu component. This component uses conditional rendering to display only when necessary. Within the component, there is an image for the close button of the side menu. <transiti ...

Share your message with BotFramework WebChat by simply clicking on the provided link

A chatbot I created using Microsoft Bot Framework has been integrated into my website through DirectLine: <div id="chatbot_body"></div> <script src="https://unpkg.com/botframework-webchat/botchat.js"></script> <script> ...

Is there a way to bypass using project() function automatically when performing a MongoDB find()?

Utilizing project() to extract specific fields from my MongoDB query using the nodeJS MongoDB driver. However, I only require the projection in certain scenarios. Therefore, if useProjection is set to false, I want the complete datasets to be returned. I& ...

Loop through the last modified file

I am currently working on a webpage that displays the "last-modified" date of each file it loads: Have you noticed how the dates are loaded one by one as the page makes calls to the header? If not, try hitting F5 to refresh the page. Is there a way to im ...

What is the best way to format a lengthy SQL query as a JavaScript variable?

I have a lengthy SQL query that needs to be converted into a JavaScript variable. The contact information is spread across separate rows using the + character. However, the SQLite plugin is displaying a parsing error: What is the correct way to format t ...

Tips for setting a background image that covers the entire screen

Exploring Next.js after working with React, I am facing a challenge in setting a full screen background image for a hero section using styled components. While I have successfully achieved this in React using styled components with code similar to the exam ...

Issue with jQuery incorrectly calculating height post-refresh

I am currently utilizing jQuery to vertically center various elements on a webpage. Due to lack of support in older versions of IE, I cannot use the table-cell CSS statement. Therefore, I am using jQuery to calculate half of the height and then position it ...

Interactive HTML5 canvas: Dragging and dropping multiple items

I'm currently working on a project that involves allowing users to drag and drop multiple objects within a specified area. To achieve this, I am utilizing the html5 canvas tag. While the functionality works smoothly when dragging and dropping a single ...

Embrace AngularJS: Employ the ".then" method and retrieve the response

In order to send a http request and receive the response of this request, I am trying to implement a mechanism where if the data is successfully saved, I can retrieve database information, and if it fails to save, I can track errors. To achieve this, I pla ...

I am having difficulty with the fadeIn animation not working as expected in my situation

http://jsfiddle.net/9w0v62fa/1/ Instead of using opacity 0 and 1 in two different places, which I find redundant, I attempted to utilize the CSS animate property. However, I couldn't get it to work. Here is my code: .btn{ background:blue; pa ...

The combination of Material UI custom TextField and Yup does not seem to be functioning properly

I am facing an issue with integrating my custom TextField into my RegisterForm along with Yup validation. Whenever I use the custom TextField, I encounter a message "⚠ Champ obligatoire" after clicking on Submit, which is not the case when using a simple ...

What is the best way to add user login information to the request pipeline in Express.js?

In my current project, I've been working on a middleware that is responsible for extracting the user model and attaching it to the request pipeline. Although I have successfully implemented a token extractor middleware that attaches the token to the r ...

The bond between TypeORM and express

I am working on establishing Many-to-One and One-to-Many relationships using TypeORM and MySQL with Express. The database consists of two tables: post and user. Each user can have multiple posts, while each post belongs to only one user. I want to utilize ...

Present the retrieved JSON data values in an alternative layout on the table

I am facing an issue with the data display in my current table setup. The data is fetched from an SQL server, encoded into JSON format, and the structure of the JSON output is causing a problem for me. You can see how it looks like here: The challenge I a ...

Steer clear of the null value in the subcomponent

There's a sub-component that I'm using for a page: <template> <div class="ll-page-wrapper"> <div class="ll-page-div"> <Page :total="data_count" :current="cur_page" @on-change="changePage"></Page> < ...