Having trouble retrieving image from API in Next.js - Error: Unable to access properties of undefined while trying to read 'map' in Next.js

I'm facing an issue with fetching an image from the API and I can't figure out what's causing it. Can anyone help me identify the problem?

On top of that, there's an error showing up in the browser indicating that the "src" property is missing when using the next/image component. The error message says: {} null

When I try to log the images in the console using console.log, it returns undefined.

function Images({images}) {
 
    
    return (
        <div>
    {images?.map((image)=> (
        <Image src={image.url}/>
    ))}    
        </div>
    )
}

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

return {
    props: {
        images,
    },
}

}

export default Images

Answer №1

You're dealing with a nested structure and the solution involves using nested maps.

function Images({ data }) {
  return (
    <div>
      {data?.length && 
        data.map((item) => item.images.map((image) => <img src={image?.url || ''} height={100} width={100} />))}
    </div>
  );
}

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

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

export default Images;

An additional tip:

If you encounter issues with next/image, make sure to include the necessary configuration in the next.config.js file as shown below:

module.exports = {
  ...otherConfigs,
  images: {
    domains: ['www.HOSTNAME.com'], // hostname of the img url
  },
};

The provided link showcases the images: https://i.stack.imgur.com/bU78c.png

Answer №2

Ensure that the variable images is an array.

If not, assign it a default value.

// getStaticProps
return {
    props: {
        images : images ?? [],
    },
}

or

function Images({ images = [] }) {...}

Answer №3

{data?.image_url?.length && data?.image_url?.map((item: any) => (<img src={item.url || 'image'} height={300} width={400} />))}

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 incorporate a next.js image onto the background design?

I've encountered an issue while attempting to create a fixed background image with a parallax effect using Tailwind CSS and Next.js Image. If you need to see an example of this in action, check out this Template Monster theme. Here's the code s ...

Error: Missing module/critical dependency required for mongoose/mongodb usage

While integrating mongoose with nextjs, I keep encountering numerous errors regarding missing critical dependencies or modules that are not found. Below is the console output: wait - compiling... warn - ./node_modules/@aws-sdk/util-user-agent-node/dist- ...

Learn how to pass an id from the query parameters to the getInitialProps function in Next.js

Looking to create a basic website that displays content from a database? Utilizing the getInitialProps function from Next.js documentation can help with server-side rendering: https://nextjs.org/docs/api-reference/data-fetching/getInitialProps#getinitialpr ...

AWS ECS + Fargate setup causing issues with Next.js CSR and GraphQL requests

I am currently working on an application using Next.js and Golang within a docker container. However, I have run into an issue with Next.js CSR graphql requests not functioning properly on AWS ECS Fargate. The SSR works fine, but the CSR request times out. ...

`fetch` functionality does not function properly when included in middleware page after deployment on Vercel

On a specific route, I have a middleware page that first checks against the backend server. Within this middleware, I am attempting to call a next.js api page using the fetch API, which then communicates with the backend. This process functions correctly i ...

Facing issues with dynamic imports in Jest and React Testing Library while testing Next.js 12? Try using SWC instead of babel for a smoother experience

I am encountering issues with testing dynamic imported components in Next.js 12. Here is some technical information: Next.js 12 uses SWC instead of Babel React 18 Jest + React Testing Library Below is an example: import styles from '@/pages/index.mo ...

Utilizing the Laravel back-end API within the getServerSideProps() function in Next.js

Currently, my setup involves using next js for the front-end and laravel for the back-end. I am attempting to make an API call to the back-end (laravel) from the getServerSideProps() method as demonstrated below: export async function getServerSideProps(co ...

What is the best way to incorporate dynamically added scripts into a document using JavaScript

Is there a way to dynamically add a script in document.js? In document.js, there is no access to props. How can a script be conditionally added? import { Html, Head, Main, NextScript } from 'next/document' export default function Document() { ...

What is the process for accessing and interpreting request body and query parameters in the next 13 API using the app router in the route.ts file?

I couldn't find a solution on this page: https://nextjs.org/docs/app/api-reference/file-conventions/route. ...

Refreshing a Next JS page with updated data from MongoDB database without needing a manual page reload

I've been working on a project where I interact with a MongoDB database from my NextJS site to display data. The goal is to implement CRUD functionality, allowing users to add new content and delete existing one directly from the site. However, there& ...

The next script functions are not compatible with the _document.js file in Next.js

I am working on a project in Next.js and I am trying to load two scripts using the next/script module within the _document.js file. However, when I place the Script tags inside the body tag in _document.js, my scripts are not executing as expected. I follo ...

Is implementing client components in Server Side pages an effective strategy for optimizing SSR performance?

In order to overcome the challenge of using client-side components in server-side pages, I made the decision to create a client-side wrapper to encapsulate these components within server-side pages. This way, I can manage all API calls and data fetching on ...

Tips on implementing local storage in cypress

I am encountering an issue with a simple test describe('Page Test', () => { it('button has "contact-next-disabled" class', () => { cy.get('.contact-next-disabled') }) }) Upon running the test, cypress ...

Deploy the Next.js app on Vercel without regenerating pages, and instead trigger the deployment only upon request

Greetings to my fellow developers, For the past year, I have been using Next.js on Vercel and so far, I am absolutely loving it. The ability to create SEO friendly React websites has been a game changer for me. However, as my website continues to grow and ...

An issue with displaying images has been identified within Next.js, resulting in an error message related to the hostname

Encountering an error when using next js Image next.config.js: module.exports = { images: { domains: ['localhost'], }, }; Error image: https://i.stack.imgur.com/RvsdH.png I am struggling to understand how to correctly set up the image ...

I noticed that when using Next.js with the `revalidate: 1` option on a static page, it is triggering two full F5 refresh actions instead of just one. I was hoping for

Currently, I have set up a blog post edit page in my Next.js project. The post pages are utilizing the Incremental Static Regeneration feature with a revalidation time of 1 second for testing purposes. In the future, I plan to increase this to a revalidat ...

Securely verifying user identity across various domains using Cross-Origin Resource Sharing (CORS) in conjunction

I am trying to make a cross-origin XMLHttpRequest from domain1.com to domain2.com. domain2.com is a NextJS application that uses NextAuth for authentication. The issue I am facing is that when I send this request, the cookies from domain2 are not being in ...

An error occurred while trying to serialize the `.res` response received from the `getServerSideProps` function in

I encountered the following issue while utilizing the getServerSideProps function to fetch data from Binance API. import binance from "../config/binance-config"; export async function getServerSideProps() { const res = await binance.balance(( ...

Issues with Paypal react and Next JS buttons failing to reflect changes in shopping cart quantities

There seems to be an issue with the React PayPal Buttons integration. Despite updating the quantity of products in the cart, the changes are not being reflected in certain components like createOrder and onApprove within the PaypalButtons props. As a resul ...

Get image data from Next.JS API and show it in the web browser

I am looking to utilize my own next.js endpoints to request an image that I can then embed into my website. Currently, the issue I am facing is that the image seems to be immediately downloaded and does not display in the browser window. import type { Next ...