Nextjs is throwing an error saying that there is a TypeError with products.map not being a

When attempting to iterate through products in a json file, I encountered the error TypeError: products.map is not a function

Below is the code snippet:

import React from "react"; import Link from "next/link";

function shop({ products }) { return (
    <div>
      <nav>
        <Link href="/">Home</Link>
        <Link href="/shop">Shop</Link>
      </nav>
      <div className="title1">
        <h1>Explore All Products</h1>
      </div>
      <>
        {products.map((product) => { return (
            <div key={product.id}>
              <Link href="">
                <h2>
                  {product.id} {product.title}
                </h2>
              </Link>
            </div>
          );
        })}
      </>
    </div>   ); }

export default shop;

export async function getStaticProps() { const response = await fetch("https://dummyjson.com/products"); const data = await response.json(); console.log(data);

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

I have tried various solutions shared on stack overflow but none have resolved the issue.

Answer №1

 > import React from "react"; import Link from "next/link";
    > 
    > function store({ items }) {   return (
    >     <div>
    >       <nav>
    >         <Link href="/">Home</Link>
    >         <Link href="/store">Store</Link>
    >       </nav>
    >       <div className="title1">
    >         <h1>Discover Our Collection</h1>
    >       </div>
    >       <>
    >         {items.map((item) => {
    >           return (
    >             <div key={item.id}>
    >               <Link href="">
    >                 <h2>
    >                   {item.id} {item.title}
    >                 </h2>
    >               </Link>
    >             </div>
    >           );
    >         })}
    >       </>
    >     </div>   ); }
    > 
    > export default store;
    > 
    > export async function fetchData() {   const response = await
    > fetch("https://samplejson.com/items");   if (response.status !==
    > 200){
    >     console.log(`Error: ${response.status}`);   }   const info = await response.json();
    >   
    > 
    >   return {
    >     props: {
    >         items: info.items, //instead of just "info"
    >     },   }; }

Answer №2

Once you hit the URL https://examplejson.com/items, a response in JSON format will be received:

{
    "items": [...],
    "count": 50,
    "start": 0,
    "limit": 20
}

To extract the desired information, focus on the items attribute and simply fetch it by utilizing the following line of code:

return { result: { items: dataset.items } };

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

Discover the method for accessing a CSS Variable declared within the `:root` selector from within a nested React functional component

Motivation My main aim is to establish CSS as the primary source for color definitions. I am hesitant to duplicate these values into JavaScript variables as it would require updating code in two separate locations if any changes were made to a specific co ...

Implementing image display in autocomplete feature using jQuery

I am currently working on a project using Spring MVC, where I am implementing a jQuery autocomplete plugin to fetch data from a JSON file generated by the server. $('#searchTerm').autocomplete({ serviceUrl: '${ctx}/search/searchAutocomp ...

Creating a dynamic video background using Html5 and CSS with a scrolling attachment

video { width: 100%; z-index: 1; position: fixed; } I tested this code and it works well, however, the video remains fixed across the entire body of the page... ...

Tips for utilizing the "get" method in React to submit a form

Is there a way to submit a form using the "get" method to an external URL in react? Similar to how it is done in HTML like in this example: https://www.example.com/form But instead, to a third party URL...? Can I achieve something like this? The goal is ...

Unusual occurrence while creating a unique identifier for a React component

I am working on creating a unique identification number for each React component, which will be assigned to the component upon mounting. Here is the approach I am taking: The callOnce function is used to ensure that a specific function is only executed on ...

Form submission requires a checkbox to be checked

I have been searching for a way to make checkboxes required. Is there a method similar to using required="required"? Currently, I generate my checkboxes in the following manner and would really appreciate any guidance on this topic. It's crucial for m ...

Delving into the World of ReactJS Routing Components and Rendering

I recently developed a basic booking app consisting of 3 essential files - App.js, Booked.js (1st child), and Details.js (2nd child). My current dilemma involves attempting to access App.js for the purpose of deleting data using the 2nd child (Detail.js). ...

What is the best way to designate unique custom login redirects based on user type?

I am facing a challenge that I can't seem to overcome. Part of the issue is my struggle to articulate it effectively with the right terminology. As a newcomer in this field, please forgive me for posing such a clumsy question. Below is an outline of ...

Guide to loading a Canvas texture in a Wavefront OBJ using three.js

Hello there! I am currently working on a project where I am using three.js to display an obj file exported from Blender and map a texture from a canvas onto it. I managed to successfully display the image in obj format, but when I tried to apply the canvas ...

What is the best way to display a single instance of a React component that is declared in multiple locations within the app?

Imagine I have 2 main components, A and B. Now, component C needs to be created inside both A and B. How can I guarantee that the same exact instance of C is generated in both places? Essentially, I want them to stay synchronized - any changes made to one ...

Exploring ways to validate the existence of a class in HTML table elements

If I want to verify if each element has a specific class when creating tables and clicking on the corresponding cells above them, This is what I have tried. However, it did not work as expected. How can I make this work correctly? What am I missing her ...

Tips for verifying the input field with specific requirements in Angular 6

There is an input field that needs to validate text based on certain logic conditions: No spaces should be allowed in the formula. The operators (and,or) must be lowercase and enclosed in curly brackets {}. The number of opening '(&apos ...

What is the best way to retrieve the scope of ng-repeat from another directive located on the same element as ng-repeat?

Is it possible to access a property from the ng-repeat scope in another directive within the same element as the ng-repeat directive? For instance, I would like to be able to use the child.class property in this scenario: <div ng-class="{{ child.class ...

What is the best way to showcase arrays in a JSON document?

I'm working on a basic AJAX code to show a JSON file stored locally using this HTML, but I keep getting an 'undefined' error. I'm opting for JavaScript instead of JQuery since I haven't delved into it yet; hoping my code is syntact ...

What is the best way to ensure that custom JavaScript and CSS files in Sphinx are always loaded with the most recent changes

Within the configuration file conf.py for Sphinx, I have specified the following: html_css_files = ['css/custom.css'] html_js_files = ['js/custom.js'] However, any alterations made to custom.js or custom.css do not immediately appear i ...

The vertical scroll position of a container with overflowing content does not correspond to the height of its elements

I have a div that has a fixed height of 155px and is set to scroll vertically when overflow occurs. Inside this div, there is an unordered list with a height of 338px. I am attempting to determine when a user reaches the bottom of that div. $('.myD ...

Ensure the validity of the Laravel Sanctum token within the Next.js middleware as a security measure for route protection

Looking to implement an authentication system in Next.js using Laravel Sanctum but running into issues verifying if a token is valid. The current middleware in Next.js only checks for the existence of a token, allowing anyone to manually create a token in ...

Error message: An uncaught promise was encountered, despite adding a catch function. I am unable to identify the issue causing this error

Why is the added catch block not functioning properly? function maxRequest(url = ``, times = 3) { // closure function autoRetry (url, times) { console.log('times = ', times); times--; return new Promise((resolve, reject) => ...

Sending an array to a component in Angular without the need for a controller

How can I pass an array to a component in Angular 1 without being inside a controller (using a component-only approach)? Currently, my starting point is: <user-list users="users"></user-list> The 'users' variable is a JavaScript arr ...

Nothing is being displayed on the screen via React

Initially, I used a function instead of a class, and the code was functioning up to a certain point. However, now it is not displaying anything at all. In my VehiclesList.js, I am generating 10 random vehicles. Here is the code snippet: import React from ...