I am unable to showcase the image at this time

Hey there, I'm having an issue with displaying an image stored inside the NextJS API folder. The alt attribute is showing up fine, but the actual image isn't displaying. When I console.log the image data, everything seems to be in place. Can anyone spot what I might be doing wrong?

Here's a peek at 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 CartItemType = {
  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<CartItemType[]>("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

Answer №1

I believe there may be an issue with the paths to your images. By default, the root of your static assets is set to public. If you have images named automatic.png and pump.png in your public folder, try modifying the response of your data API to reflect this change.

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

) }

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

Extract distinct values along with their respective counts from an array containing objects

Upon receiving a JSON request containing an array of objects with two properties, the task at hand is to extract the unique values along with their respective quantities. The following JSON data is being sent through Postman: [ {"name": "First value" ...

I am curious if there exists a VSCode plugin or IDE that has the ability to show the dependencies of TypeScript functions or provide a visual representation

Are there any VSCode plugins or IDEs available that can display the dependency of TypeScript functions or show a call stack view? I am looking for a way to visualize the call stack view of TypeScript functions. Is there a tool that can help with this? Fo ...

Guide on using JSZip and VUE to handle an array of promises and store them in a local variable

My lack of experience with async functions has me feeling a bit lost right now... I'm attempting to loop through files in a folder within a zip file using JSZip, store these files in an array, sort them, and then save them to a local variable for furt ...

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 ...

how to change class on vue function result

I need a way to display the content stored in requestData as li elements. Each list item should have an onclick function that, when clicked (selected), adds a specific value from a reference to an array. If clicked again (unselected), it should remove the ...

How can I add a string before a hashtag(#) in AngularJS URLs?

Can we add a prefix to the # symbol in angular.js URLs? For instance: let's say we have a site: http://example.com/ then when I click on the CSharp page, it redirects to http://example.com/#/csharp when I click on the AngularJS page, it redi ...

Add a SlideUp effect to the .removeClass function by using a transition

Looking to incorporate a SlideUp transition while removing the class with .removeClass. This script handles showing/hiding the navigation menu based on page scroll up or down. I am looking to add a transition effect when the navigation menu hides. Check ou ...

Ajax alert: The index 'id' is not defined

I'm currently learning PHP and scripting, but I am encountering some difficulties when it comes to sending information to PHP. I would appreciate any help you can offer. Thank you for your assistance. Here is the issue at hand: Error Message: Noti ...

Numerous requests for GetStaticProps are causing my application to freeze during the build process and result in a server error

I need to compile a long list of products and I want to fetch data using node in order to build the page statically for faster loading on the homepage. The issue arises when I try to make over 80 requests with GetStaticProps method. The code below works ...

Transforming a string in AngularJS to a "controller as" approach using $parse

How can I modify foo.callbacke to reference the timerController.callbacke method? <div ng-app="timerApp" ng-controller="timerController as foo"> <div ng-repeat="item in [1,2,3,4]"> <div watcher="{'seconds': 'foo.callbacke ...

Adjust the background color of the table header in Google Charts

Is it possible to dynamically change the background color of the header row (and rows) in Google Charts based on values from a PHP database? The documentation suggests using the following code: dataTable.setCell(22, 2, 15, 'Fifteen', {style: &a ...

Attempting to decode JSON data

I'm new to node.js and trying to learn how to send a JSON object using REST. However, I keep getting an error message that says "SyntaxError: Unexpected token  in JSON at position 0". I've checked the JSON using an online validator and it seem ...

Setting form values using Angular 9

I am currently facing a challenge that I could use some assistance with. My dilemma involves integrating a new payment system, and I seem to be encountering some obstacles. Here is a snippet of what I have: options: PaystackOptions= { amount: 5000, emai ...

Techniques, modules and functions in Javascript

How should I properly document this code snippet: // Define a collection of colors with methods colors = { // Define method for color red "red" : function() { // Do something... } // Define object for color black "black" : { // Add ...

experiencing difficulties in retrieving the outcome from a sweetalert2 popup

function confirmation() { swal.fire({ title: "Are you absolutely certain?", text: "You are about to permanently delete important files", type: "warning", showCancelButton: true, show ...

Guide to extracting the values associated with a specific key across all elements within an array of objects

My goal is to retrieve the values from the products collection by accessing cart.item for each index in order to obtain the current price of the product. const CartSchema = mongoose.Schema({ userId: { type: mongoose.Schema.Types.ObjectId, ...

TS2688 Error: Type definition file for 'keyv' is missing

The automated code build process failed last night, even though I did not make any changes related to NPM libraries. The error message I received was: ERROR TS2688: Cannot find type definition file for 'keyv'. The file is in the program because: ...

Transformation from a class component to a function component in React JS

I have a class component that I need to convert into a functional component. So, I started by refactoring the constructor. Below is the original class component: class EventCalendar extends React.Component { constructor(props) { super(props) ...

Partial view remains stagnant despite successful ajax post completion

I am currently in the process of developing a system that will showcase uploaded images from a file input into a specific div within my view. (with intentions to incorporate document support in the future) The challenge I am facing is that the partial vie ...

Retrieve the $http data from a function that is external to it

Apologies if the title is confusing, it's hard to explain in a different way. The situation I have is... app.controller('viewProductController', ['$scope', 'dataFactory', '$routeParams', function($scope, dat ...