Why won't my fetch API function properly in my Next.js project?

import { GetServerSideProps } from 'next';

type Product = { //Product variables
  id: number;
  title: string;
  price: number;
  thumbnail: string;
};

interface ProductsProps {
  products: Product[];
}

export default function Products({ products }: ProductsProps){
  return (
    <main>
      <h1 className="productHeader">Our Products</h1>
      <div className="products">
        {products && products.map((product) => (  `//mapping`
          <div className="card" key={product.id}>
            <p>{product.thumbnail}</p>          `Product info`
            <p>{product.title}</p> 
            <p>price:{product.price}$</p>
          </div>
        ))}
      </div>
    </main>
  );
};

export const getServerSideProps: GetServerSideProps = async () => {   'fetching API'
  const res = await fetch('https://dummyjson.com/products');
  const products = await res.json();

  return {
    props: {
      products,
    },
  };
};

I attempted to retrieve data from the 'https://dummyjson.com/products' API, but unfortunately, I am not seeing any product information on the website. The API should provide details like product name and thumbnail images. Despite my efforts, the products are not displaying as expected on the site, indicating that there may be an issue with how I implemented the API fetch.

Answer №1

If you happen to be using the app router provided by Next.js, please note that the getServerSideProps function will not function as expected.

According to the documentation for migrating to Next.js 13,

We are now able to colocate our data fetching within our React components in the app directory using Server Components. This results in sending less JavaScript to the client while preserving the server-rendered HTML content.

Link to Next.js documentation on app router migration


To resolve this issue, you can convert your component into a server component and utilize a fetch operation that will be executed on the server side rather than the client side.

type Product = { //Interface defining Product structure
  id: number;
  title: string;
  price: number;
  thumbnail: string;
};

async function getData() {
  const res = await fetch('https://dummyjson.com/products');
  return await res.json() as Promise<Product[]>;
};

export default async function Products(){
  const products = await getData()

  return (
    <main>
      <h1 className="productHeader">Our Products</h1>
      <div className="products">
        {products && products.map((product) => (
          <div className="card" key={product.id}>
            <p>{product.thumbnail}</p>
            <p>{product.title}</p> 
            <p>price:{product.price}$</p>
          </div>
        ))}
      </div>
    </main>
  );
};

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

fill the designated column in accordance with the specific criteria

Is there a method to automatically fill in a specific column based on certain conditions? I am looking to populate the column labeled [Last] when the column index is 1 and the corresponding name is [First]. import {Component, OnInit} from '@angular ...

Using .on('mouseover', d => ..) does not yield the same `d` value as using .attr('foo', d => ..) in D3.js

I'm facing an issue with a mouseover tooltip in Observable that seems to fail when I transfer it to a Grafana plugin using React, D3, and Typescript. The technique I followed can be found in this article: Link to Article To simplify the code and deb ...

Find any consecutive lowercase or uppercase letter and include one more

I have a task in Javascript that I need help with. The goal is to insert a special character between a lowercase and uppercase letter when they are matched together. For example: myHouse => my_House aRandomString => a_Random_String And so on... T ...

Converting JSON into Typescript class within an Angular application

As I work on my app using angular and typescript, everything is coming together smoothly except for one persistent issue. I have entity/model classes that I want to pass around in the app, with data sourced from JSON through $resource calls. Here's ...

React waitforelement fails to work in conjunction with asynchronous calls

I am currently experimenting with a straightforward login form that includes an asynchronous call in React using TypeScript and classes. Here is how my component appears: import * as React from 'react'; import { LoginService } from './servic ...

Dealing with the "empty_url_error" while configuring a Next.js project with Microsoft Azure AD

I've been working on setting up Microsoft Azure AD authentication, and I believe I have filled in all the required fields correctly. However, despite my efforts to avoid sharing any confidential information, I keep encountering an "empty_url_error" me ...

Transforming Boolean data types into text within an Angular 2 client-side application

Query I'm currently working on retrieving data from an API and displaying it in a table. One of the columns includes a status attribute that returns either true or false values. However, I would like to display "Active" or "Block" instead on the clie ...

Adding Relative URLs Automatically to .angular-cli.json is a simple process that can be easily

Is there a way to automatically have Angular-Cli (Angular-4) append URL's to Styles or Scripts when adding external libraries with npm install --save into .angular-cli.json? Currently, we have to manually search through the node_modules folder to fin ...

Exceeding the maximum number of concurrent connections with Pusher caused issues

As I work on developing a real-time chat application using the Pusher library in Next.js, I encounter an issue with multiple concurrent connections being created while exploring the website. Upon reading an article by Pusher titled Why Am I Seeing More Ch ...

Is it possible for TypeScript to automatically determine the specific type that was used in a union type parameter?

I need some help with a utility function I'm working on that can remove a specified number of elements from either a string or an array. My goal is to have the compiler determine whether the return value should be a string or an array based on what is ...

`How to cleverly fake dependencies with symbols in Jest, Vue3, and Typescript?`

I am faced with the following scenario: // symbols.ts - Injection Key defined as a Symbol export const FAQ_SERVICE: InjectionKey<FAQService> = Symbol('FAQService'); // main.ts - globally provides a service using the injection key app.provi ...

Creating an interface for writing types in Firebase functions/storage/database

What are the TypeScript types for Firebase functions, storage, and admin? I'm fairly new to TypeScript and currently in the process of updating my JavaScript code to TypeScript. Within my code, I am generating a context object. const context = { ...

Implement new interface methods on-the-fly

I am seeking a way to dynamically incorporate methods that are defined in an interface. Initially, I considered using the index signature approach, but unfortunately, not all methods have the same signature. My objective is to preserve all type information ...

Am I effectively implementing async await in TypeScript?

I'm not quite sure if I'm using the async/await functionality correctly in my TypeScript and Protractor code. Looking at the code snippet below, the spec uses await to call the page object, which itself is an async/await function. The page object ...

Error encountered in Angular CLI: Attempting to access property 'value' of an undefined variable

I am encountering an issue while trying to retrieve the values of radio buttons and store them in a MySql database. The error message I receive is TypeError: Cannot read property 'value' of undefined. This project involves the use of Angular and ...

Restrict or define the acceptable values for a key within an interface

In search of defining an interface that allows for specific range of values for the key. Consider this example: interface ComparisonOperator { [operator: string]: [string, string | number]; } The key can take on values such as >, >=, !=, and so ...

The Socket.io socket listener in the Next.js API is failing to refresh and update properly

I am working on a Next.js project that includes a basic implementation of Socket.IO. Check out the code snippet below: // pages/index.tsx let socket: Socket; const Home: NextPage = () => { useEffect(() => { async function initializeSocket() { ...

Implement Role Based Authorization in Auth0 and NextJS

I recently developed a web application using NextJS and integrated Auth0 for authentication. While the user login, logout and basic user information functionalities are working fine, I am facing an issue with retrieving user roles. Currently, I am retrie ...

Error: Unable to retrieve the name of the element because it is undefined

After updating to the latest version of NEXTUI, I encountered a new issue. Whenever I click on a NEXTUI Button that is nested within a Link from Next.js, I receive an error message stating: TypeError: Cannot read properties of undefined (reading 'node ...

My attempts to implement multi-container service deployment using NextJS and a backend node app have been unsuccessful

Currently, I am delving into the world of docker. Within my repertoire, I possess a mix of a next.js app and a node.js app. Within my next.js application, specifically in page.tsx, I have incorporated a call to my backend API. export const revalidate = 0; ...