Error: Attempting to access 'map' property of an undefined variable in NEXTJS

I've been struggling to retrieve an image from this API using getStaticProps, but for some reason I can't seem to make it work.

In my code snippet, if I add a question mark like this, the console returns 'undefined'. What could be causing this issue?

<div>
  {hotelPics.map((hotelpic)=> (
  <Image src={hotelpic.url} />
  ))}
</div>

Here is the code snippet:

import Image from 'next/image';
import React from 'react'


function Images({hotelPics }) {
 
    console.log(hotelPics);
    
    return (
        <div>
    {hotelPics.map((hotelpic)=> (
        <Image src={hotelpic.url}/>
    ))}    
        </div>
    )
}

export async function getStaticProps() {
    const res= await fetch ('https://obmng.dbm.guestline.net/api/hotels?collection-id=OBMNG')
    const hotelPics = await res.json()

return {
    props: {
        hotelPics,
    },
}

}

export default Images

Answer №1

getStaticProps function is executed at build time, so it's important to monitor the isFallback variable.

Additionally, there is a nested images array within the hotelPics array that is returned by the getStaticProps.

import Image from 'next/image';
import { useRouter } from 'next/router';
import React from 'react'

function Images({ hotelPics }) {
  const router = useRouter();
  if (router.isFallback) {
    return <h1>Loading...</h1>;
  }

    //console.log(hotelPics.images)
    return (
        <div>
        {hotelPics.map((hotelpic) => (
            hotelpic.images.map((image) => (
              //replace here with Image tag
              <p key={image.url}>{image.url}</p>
              )
            )
        ))}    
        </div>
    )

}

export async function getStaticProps() {
    const res= await fetch ('https://obmng.dbm.guestline.net/api/hotels?collection-id=OBMNG')
    const hotelPics = await res.json()

return {
    props: {
        hotelPics,
    },
}

}

export default Images

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

Registering components globally in Vue using the <script> tag allows for seamless integration

I'm currently diving into Vue and am interested in incorporating vue-tabs into my project. The guidelines for globally "installing" it are as follows: //in your app.js or a similar file // import Vue from 'vue'; // Already available imp ...

What is the process for submitting and storing a collection of files in a database as a list?

I am trying to implement a feature in my MVC project where users can upload multiple files and see them listed before submitting the form. However, I am facing some challenges with finding a solution for this. Demo: My goal is to allow users to add multi ...

Need to clear cache following a content update in Sanity?

I've integrated Sanity as my content management system and Next JS for the frontend of my website. To ensure that my site can handle a decent amount of traffic, I know caching is necessary. However, there's a challenge when it comes to editors m ...

Using AngularJS to auto-fill input and textarea fields

In order to test local storage, I created a ToDo list using angularJS. Within my mainController, the following code snippet is present: $scope.saved = localStorage.getItem('todos'); $scope.todos = (localStorage.getItem('todos') !== n ...

Controller data is being successfully returned despite breakpoints not being hit

While working with knockout Java-script, I encountered a perplexing issue. I have an API call to a controller which has several methods that are functioning correctly. However, when I set a break point on a specific method, it never gets hit. Strangely, da ...

What is the best way to retrieve the parent of the initial jQuery object?

At the bottom of a lengthy table containing multiple button.enter-match elements, I am using the following code: $("button.enter-match") .button() .on('click', function() { $("form.enter-match").dialog({ modal: true, height: ...

What causes the burger dropdown to be concealed by additional content?

While viewing my menu on an iPhone SE in responsive mode, I noticed that all of my burger menu items are hidden except for the one that fits perfectly in the space between my header and main content. I am using Mantine with NextJS, and my layout structure ...

Is there a way to import a module generated by typescript using its name directly in JavaScript?

I am trying to bring a function from a typescript-generated module into the global namespace of JavaScript. The typescript module I have is called foo.ts: export const fooFn = (): string => { return "hello"; }; Below is the structure of my HTML file ...

How to download a file using AJAX in Laravel?

Is there a way to download a CSV file within an ajax call? I have an ajax request in my Laravel controller that successfully retrieves the file contents in the response. However, I am facing issues with actually downloading the file. Laravel controller c ...

Tips for adjusting the color of a <a> tag upon clicking, which remains unchanged until the URL is modified

My goal is to maintain the color of a link when it is clicked. Currently, hovering over the navbar link changes it to greyish, but I want it to remain a different color after clicking on it. I am implementing this using the react-router-dom library for the ...

Presentation: Troubleshooting Ineffective CSS3 Transitions

I have created a basic slideshow that can accommodate multiple images. Clicking on an image should move to the next slide, and once the last image is clicked, it should loop back to the first slide. The functionality of transitioning between slides seems ...

Incorporate action icons (such as edit and delete) into a table in React.js using material-ui

Within my existing table, I utilized a library known as react-bootstrap-table-next This library effectively displays data in a table format with values originating from a JSON response Now, my goal is to integrate an Action column that includes options f ...

Discovering the reason behind a DOM element's visual alteration upon hovering: Where to start?

Visit this page, then click on the next button to navigate to the time slots section. As you hover over any time slot, you will notice a change in appearance. Despite inspecting Chrome's developer tools, I was unable to locate a style with a hover dec ...

Tapping on the invisible picture

I currently have a square image of a car with a transparent background. My goal is to make the car clickable so that when I click on it, it triggers an action. However, I also want the transparency around the car to allow clicks to go through and affect th ...

Employ a variable within the fetch method to retrieve JSON data

Currently, I am in the process of developing a system that extracts specific information from a JSON file based on user input. One challenge that I am facing is how to incorporate a variable into the designated section of my code; fetch( ...

Loading animation reminiscent of a whirlpool, similar to the movement

In my quest for the perfect animation, I have scoured far and wide. Unfortunately, the one I found at http://jsfiddle.net/pedox/yed68/embedded/result/ is created using css, which many browsers do not yet support fully. I also explored , but found it to be ...

Scrolling through a list of objects in a React component to display a vertical lineup of items including the name and logo

Currently, I am working on developing a vertical scrolling ticker/item list that showcases both the name and logo of each item within an array. Initially, I had set up a scrolling ticker solely with names using webkit animations on styled components. Howev ...

What is the best way to store font size and background color settings in local storage?

After following the solution provided for a similar issue on SO, I am facing a problem where no changes are reflected when using the select box or color picker to modify the font size or background color. I have commented out the lines that were added in a ...

Initializing start scripts in the package.json file

When launching my react app locally, I need to execute three commands: cd react-web npm run postinstall export REACT_APP_CUSTOMER_ENVIRONMENT=xxx npm start After running these commands, the application server starts on localhost:3000. For the start script ...

Adjust the text color of ASP.Net Label based on the presence of a hyphen

I need help changing the text and font color of my ASP.net label based on its content. The label displays a percentage change, and I want negative numbers to be shown in green and positive numbers in red. However, when I try to implement this, I keep enc ...