Home > Back-end >  I'm not able to display image
I'm not able to display image

Time:07-25

please am trying to display a data I store inside NextJS API folder that has an image inside but the image is not showing, only displaying the alt attribute but every other data is showing, when I console.log the image I will see the data. what am I doing wrong?

Here’s my code // pages/api/data.tsx file

import type { NextApiRequest, NextApiResponse } from 'next'

type Data={ 
  id: number,
  name: string,
  description:string, 
  image:string,
  price:number
}[]


export default function handler(
  req: NextApiRequest,
  res: NextApiResponse<Data>
) {
  res.status(200).json(
    [
      {
        id:1,
        name: "pump control",
        image: "/public/automatic.png",
        price: 20000,
        description: "automatic pressure control for water regulator"
        },
        {
          id:2,
          name: "Automatic pump control",
          image: "/public/pump.png",
          price: 20000,
          description: "automatic pressure control for water regulator"
        }
    ]
  )
}

items.tsx file

import axios from "axios"
import useSWR from "swr"
import Image from "next/image"
import { useRouter } from "next/router"

export type CartTypeItem ={
  id:number
  name:string
  image:string
  amount:string 
  price:number 
  description:string 
}

const Items:React.FC = () => {
    const fetcher = (apiUrl:string) => axios.get(apiUrl).then(res => res.data)
    const router = useRouter()

    const {data, error} = useSWR<CartTypeItem[]>("http://localhost:3000/api/data/", fetcher)

    console.log(data)

  return (
    <div>
        {data?.map(item => (
          <div key={item.id}>
            <Image loader={()=>item.image} src={item.image} alt={item.name} width={100} height="70" />
          </div>
        ))}
    </div>
  )
}

export default Items

CodePudding user response:

i think there is a problem with your images paths by default the root of your static assets is public if you have automatic.png and pump.png in your public folder modify the response of your data api to this and it will work

  res.status(200).json(
[
  {
    id:1,
    name: "pump control",
    image: "automatic.png", // remove /pulic/
    price: 20000,
    description: "automatic pressure control for water regulator"
    },
    {
      id:2,
      name: "Automatic pump control",
      image: "pump.png",  // remove. /public 
      price: 20000,
      description: "automatic pressure control for water regulator"
    }
]

) }

  • Related