Challenges with fetching data from APIs in NextJs

I am currently working on a basic NextJs TypeScript application with the app router.

The following code is functioning correctly:

export default async function Page() {
  const res = await fetch("https://api.github.com/repos/vercel/next.js");
  const data = await res.json();

  return (
    <>
      <div>Hello from GetData</div>
      <div>
        <p>{data.id}</p>
      </div>
    </>
  );
}

However, changing the API URL to the following stops it from working:

https://jsonplaceholder.typicode.com/posts/1 or any other API such as and https://jsonplaceholder.typicode.com/users

Moreover, I have implemented types for the endpoints to receive an array in response.

type User = {
  id: number;
  name: string;
};
const data: User[] = await res.json();

https://i.stack.imgur.com/uDWEs.png

Console error encountered:

https://i.stack.imgur.com/8dlTA.png

Browser error shown:

Answer №1

When working with React/Next, it's important to remember that components are not inherently designed to be asynchronous. While it is possible to turn a functional component into an asynchronous function, it may not behave as expected. React anticipates components to return JSX synchronously, so utilizing asynchronous functions can lead to unexpected behavior. It's unclear how the provided code functions in the initial scenario, and based on what I know, it shouldn't work as intended.

If you need to fetch data using a functional component, consider employing the useEffect hook along with asynchronous functions:

export default async function Page() {
  const [data, setData] = useState(null);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await fetch("https://jsonplaceholder.typicode.com/users/1");
        const data = await response.json();
        setData(data);
      } catch (error) {
        console.error("Error fetching data:", error);
      }
    };

    fetchData();
  }, []);

  return (
    <>
      <div>Hello from GetData</div>
      {data && (
        <div>
          <p>{data.id}</p>
        </div>
      )}
    </>
  );
}

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

Is it possible to use JavaScript to click on a particular point or element within a canvas?

Is there a way to trigger a click at a specific point on a canvas without direct access to the code that generates it? I've attempted using coordinates, but haven't had any success. Any alternative suggestions would be appreciated. UPDATE: To pr ...

"Contrasting the Execution of a JavaScript Function in a .js File Versus an HTML

I'm struggling with calling a JavaScript function inside an HTML page. Interestingly, when I move the function into an external file and link it, everything works perfectly. Can someone provide assistance in resolving this issue? Below is the content ...

Is it possible to center the image and resize it even when the window is resized?

My goal is to position an image in the center of the screen by performing some calculations. I've tried using: var wh = jQuery(window).innerHeight(); var ww = jQuery(window).innerWidth(); var fh = jQuery('.drop').innerHeight(); var fw = jQ ...

Automatically generated list items are failing to react to the active class

I am facing an issue with two divs in my project. The first div uses the Bootstrap class list-group and is populated with a basic example provided by Bootstrap. The second div is supposed to be populated with list-group-items obtained from an AJAX GET requ ...

Upon calling the method, an undesirable page refresh occurs

I have been experimenting with dynamically generating additional input fields using vuejs when a user clicks a button. Initially, my code functions properly by creating more fields, but unexpectedly the page refreshes automatically, resetting the user&apos ...

Scrapy-splash seems to be encountering difficulties in extracting elements during the scraping process

My attempt to extract data from this Why is Splash not working here? Does anyone have a solution for me? Your assistance will be highly appreciated! ...

Using javascript to generate fresh dictionaries

Struggling to translate a C# "function" into JavaScript - any advice or tips? Here is the C# snippet: var parameters = new Dictionary<string,string> { { "link", "http://mysite.com" }, { "name", "This is an test" } }; I believe I need to ut ...

What is the method for assigning a value to a JSON object using data from another JSON object?

I am faced with the task of setting the seqNo property in one JSON object, b, based on the id from another JSON object, a. How can I achieve this? var a = [{id: "Make", seqNo: 4}, {id: "Model", seqNo: 1}, {id: "XModel", seqNo: 2 ...

jQuery Modal activated only once upon clicking

Recently, I've been experiencing a frustrating issue that's giving me a splitting headache. Despite scouring this forum for answers, my problem persists. Here's the situation: I have a button that triggers modals. Upon first click after refr ...

In internet explorer with AJAX, the UI is refreshed by Javascript only when an alert() function is triggered

Having an issue in Internet Explorer, works perfectly in Firefox. There is a javascript function that updates the UI (screen content) before an AJAX call. However, it does not update the UI unless an alert box prompt is used. Without the alert box, the UI ...

Unlocking $refs with the Composition API in Vue3 - A step-by-step guide

I am currently exploring how to access $refs in Vue 3 using the Composition API. In my template, I have two child components and I specifically need to obtain a reference to one of them: <template> <comp-foo /> <comp-bar ref="ta ...

A guide to resizing images in Node.js prior to using the writeFile function

var file_path = files.file.path; fs.readFile(file_path, function (err, data) { fs.writeFile(file_path, data, function (err) { res.end(JSON.stringify({ message: 'file uploaded successfully', success: true }); }); }); I exp ...

I encountered a validation error and a 404 error while trying to input data into all fields. Kindly review and check for accuracy. Additionally, I have included an

click here for image description Despite providing all details in the form fields, I keep receiving an error message prompting me to enter all fields... I am also encountering a "/api/user 404 Not Found" error and unsure of the reason. Interestingly, wh ...

The initial res.body object in NodeJS is enclosed in quotation marks

I've hit a roadblock while working on my social media website project using the MERN stack. Despite scouring the internet, I haven't been able to find a solution to the issue at hand. While following an online course, I encountered a problem tha ...

Timeout for jQuery animations

My jQuery animation script is causing an issue where it does not finish the animation before returning to the parent function. Specifically, the JavaScript code changes a background color, calls the animate function, the animation starts but doesn't c ...

What is the best method for retrieving data from a specific collection in MongoDB?

Within the code snippet below, on the 4th line, 'Messages' is the name of my MongoDB collection that I created in another file. When I attempt to retrieve data from this collection, no errors occur. However, when I specify the name of a differen ...

Error caused by live data dynamic update on Highstock chart: Cannot access property 'info' of undefined

Utilizing Laravel, I was able to create Highcharts by consuming data from a Rest API link (Spring app) at . The data is currently displayed statically, but I want to dynamically visualize it on charts. I attempted to follow this example on Fiddle and inte ...

JavaScript allows for inserting one HTML tag into another by using the `appendChild()` method. This method

My goal is to insert a <div id="all_content"> element into the <sector id="all_field"> element using Javascript <section id="all_field"></section> <div id="all_content"> <h1>---&nbsp;&nbsp;Meeting Room Booki ...

An issue has occurred on the server: The response.status function is not recognized as a valid function

import { PrismaClient } from '@prisma/client'; const prisma = new PrismaClient(); export const GET = async (req, response, next) => { try { console.log('Connected to Database via Prisma'); const movies = await prisma.movi ...

Trouble linking JavaScript and CSS files in an Express App

Could someone assist me in understanding what is causing my code to malfunction? Why is it that my javascript and css files do not execute when the server sends the index.html file to the browser? I have a simple setup with an html page, javascript file, ...