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

Angular 4 in combination with ngx-datatable is showing a 404 error for the @swimlane/ngx-datatable package

Just starting out with Angular and I kicked things off by running this command: git clone https://github.com/angular/quickstart appName I've made the upgrade to Angular 4 and everything seems to be in order. Here's the output I got after running ...

Tips for eliminating inline CSS usage in React

Is it possible to avoid using inline CSS in React when styling an element like this? const dimensionStyles = { width: 10, height: 20 }; <div className="point-class" style={{ width: dimensionStyles.width + "px", height: ...

How to Show Concealed Text in Material UI Multiline TextField and Obtain Unveiled Text

I am currently using the Material UI TextField component to create a multiline input for messages. My aim is to display a masked version of the text in the GUI while retaining the unmasked text value for processing purposes. Below is the code snippet for ...

Tracking user session duration on a React Native app can be achieved by implementing a feature that monitors and

I'm currently focusing on tracking the amount of time a user spends on the app in minutes and hours, and displaying this information. I have successfully implemented the functionality to count minutes, but I am struggling to figure out how to track wh ...

OAuth authentication in Next.js

I'm brand new to Next.js and React, so I'm a little unclear on how to approach this: We're building an app with Next.js... We'll have APIs that the client-side code will call to fetch server data. My assumption is that the source code ...

The data structure '{ variableName: string; }' cannot be directly assigned to a variable of type 'string'

When I see this error, it seems to make perfect sense based on what I am reading. However, the reason why I am getting it is still unclear to me. In the following example, myOtherVariable is a string and variableName should be too... Or at least that&apos ...

What is the proper way to declare app.use using TypeScript with the node.js Express module?

I am working on a node.js app that utilizes typescript with express. In my code, I have defined an error middleware function as shown below: app.use((error:any, req:Request, res:Response, next:NextFunction) => { res.status(500).json({message:error.m ...

Encountered a unique error code "TS1219" in Visual Studio

Recently, I made some changes to the architecture of my UI project and encountered a slew of errors (TS1219 and TS2304). Could the culprint be a poorly configured tsconfig.json file, or is it something else entirely? Despite encountering no issues when dec ...

Is there a way to exclusively view references of a method override in a JS/TS derived class without any mentions of the base class method or other overrides in VS Code?

As I work in VS Code with TypeScript files, I am faced with a challenge regarding a base class and its derived classes. The base class contains a method called create(), which is overridden in one specific derived class. I need to identify all references ...

What is the process for obtaining the URL type for Higher Order Components in NextJS?

When building a component with a Link, I am struggling to properly define the type for the href prop. import React from "react; import Link, { LinkProps } from "next/link"; type MyComponentProps = { href: Pick<LinkProps, "href&quo ...

When set to synchronize:true in Typeorm, any changes to an entity will result in the many-to

As a newcomer to typeorm, I've encountered a peculiar issue with the synchronize: true setting in my ormconfig.js. Whenever I make changes to an entity with a Many-to-Many relationship, any data present in the join table prior to the entity modificati ...

Guide to preserving canvas state in React?

I am currently working on a drawing application that allows users to draw lines on a canvas. The functionality is such that the line starts drawing on the first click, continues as the mouse moves, and stops on the second click. However, each time a user ...

What steps do I need to take for webpack to locate angular modules?

I'm currently in the process of setting up a basic application using Angular 1 alongside Typescript 2 and Webpack. Everything runs smoothly until I attempt to incorporate an external module, such as angular-ui-router. An error consistently arises ind ...

Utilizing Zustand state management with Next.js 13.4.12 for routing and server-side rendering, enhanced with local storage

My Zustand store code looks like this: import create from "zustand"; import { persist } from "zustand/middleware"; const useProjectStore = create( persist( (set) => ({ selectedProject: null, setSelectedProject: (pr ...

The logic behind combining elements from two arrays in JavaScript/TypeScript

Explanation of two different array formats const arr1 = [ { "elementName": "one" }, { "elementName": "two" } ] const arr2 = [ { "type": "RPT_PROPERTY_DEMOGRP", "values": [ { "label": "HH" }, { " ...

Next-Auth is the undeniable go-to for invoking the signIn method

I recently came across a helpful YouTube tutorial that explained how to integrate next-auth into a nextjs JavaScript project. If you're interested, you can watch the video here. Following the tutorial went smoothly for me until I reached the part whe ...

TS2559: Type 'String' lacks any common properties with type 'object'

When working with TypeScript, I encountered an issue with a map defined as shown below that is intended to accept (key, value) pairs of (string, anything). let map = new Map<String, Object>() Upon attempting to insert a (key, value) pair into the ma ...

executing code on each of the sub-routes within Nextjs

Within my file structure, I have various folders such as auth and panel. In the panel folder, there are additional subfolders like exam, article, and project. I am looking to execute a code or function across all routes within the panel folder. For insta ...

Choosing to overload the plainToClass function may result in a type error

I've been tasked with compiling an angular project that contains mostly code written by someone else. Although the example below compiles successfully on one machine, it throws an error on different machines. import { plainToClass } from 'class ...

The testString's dependencies are unresolved by Nest

Encountered Problem: Facing the following issue while running a unit test case Nest is unable to resolve the dependencies of the testString (?). Please ensure that the argument SECRET_MANAGER_SERVICE at index [0] is available in the context of SecretMa ...