Retrieving image URL from JSON in the latest version of NextJS

I created a getData.ts file for fetching data in a certain format:

export async function getData(){
    const res = await fetch("http://localhost:3001/projects")
    return res.json()
  }

The data structure I was aiming to retrieve looks like this:

    "projects":[{
        "title": "Project 1",
        "description": "Description 1",
        "tags": ["example", "notReal", "placeholder", "lol", "rofl"],
        "imageURL": "project1IMG"
    },{
        "title": "Project 2",
        "description": "Description 2",
        "tags": ["you", "get", "the", "idea"],
        "imageURL": "project2IMG"
    },

For displaying all the projects, I designed a Projects component which utilizes fragments:

import React from "react"
import { getData } from "@/lib/getdata"
import Project from "./project"

export default async function Test() {
    interface projectType{
        title: string,
        description: string,
        tags: [],
        imageURL: string
    }


    const projects: projectType[] = await getData()
    return (
        <section className="group">
        <div>
            {
                projects.map((project, index) => (
                    <React.Fragment key={index}>
                    <Project {...project} />
                    </React.Fragment>
                ))
            }
        </div>
    </section>
      )
}

However, I am struggling with referencing images stored in @/public while hosting JSON on a different server...

Here is the basic structure of each project without styling applied:

import Image from "next/image"

type ProjectProps = typeof projectsData[0]

export default function Project({ 
    title, 
    description, 
    tags, 
    imageURL,
}: ProjectProps){
    return (
       <div>
        <h1>{title}</h1>
        <p>{description}</p>
        <ul>
            {tags.map((tag: string, index: number) => (
                <li
                key={index}>{tag}</li>
            ))}
        </ul>
      <Image 
        src={imageURL}
        alt="placeholder"
        width="100"
        height="100"  
        /> 
        </div>
    )
}

(extra points for refining my TypeScript declarations)

I have tried various approaches but it seems like there is a crucial element missing in my logic...

Answer №1

Solution now in place

The JSON data points to the file:

"imageURL": "project1.png"

and my import method is as follows:

src={`/${imageURL}`}

This method is effective...

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

analyze 2 arrays and identify distinct variances

Consider having two different sets var firstSet = [{"id":1},{"id":3},{"id":5}] var secondSet = [{"id":1},{"id":2},{"id":3},{"id":4}] var missingValues = []; for(var x=0; x < firstSet.length; x++) { for(var y=0; y < secondSet.length; y++) { ...

Combining JsonResult and delivering a unified outcome in C#

I am looking to merge multiple JsonResults into a single named list for use in angularJS. Here is the function I have been working with: List<AdminBundle> abundleList = new List<AdminBundle>(); aBundleFetch.ListType = Constants.Board; Func< ...

What is the best way to reference a component variable property within its template without explicitly stating the variable name?

Suppose my component is managing an instance of the following class: class Person { firstName: string; lastName: string; age: number; } Is there a way to directly reference its properties in the template like this: <p>{{firstName}}</p> & ...

Troubleshooting Azure typescript function: Entry point for function cannot be determined

project structure: <root-directory> ├── README.md ├── dist ├── bin ├── dependencies ├── host.json ├── local.settings.json ├── node_modules ├── package-lock.json ├── package.json ├── sealwork ...

Refine JSON data using user input in PowerShell

I have user input that is separated by commas, and I am using the split function to extract different values. Additionally, I have an API that provides data in JSON format. My goal is to filter the data from the API's JSON based on the user input. He ...

What TypeScript syntax is similar to Java's "? extends MyClass" when using generics?

How can we indicate the TypeScript equivalent of Java's ? extends MyClass? One possible way to achieve this is: function myFunc <TComponent extends MyBaseClass>(param: ComponentFixture<TComponent>) {} Is there a more concise alternative ...

Unable to transmit JSON using a POST request in conjunction with Jackson

Here is my entity class structure: @Entity @Table(name = "menuitem") public class MenuItem { @Id @GeneratedValue(strategy=GenerationType.IDENTITY ) @Column(name = "id") private Integer id; @Column(name = "title") private String title; @Column(name = " ...

Getting the ng-view feature in AngularJS to function properly

Searching for a solution to create a single page application using angularjs. Successfully set up routes and partial pages are loading in ng-view properly. The struggle is with loading external json data - it was working before but now I can't seem to ...

Angular 4 yields an undefined result

I'm currently working on this piece of code and I need help figuring out how to return the value of rowData in this scenario. private createRowData() { const rowData: any[] = []; this.http .get(`/assets/json/payment.json`) .toPromise() .then(r ...

Exploring the Connection with JSON-server

While creating a simulated API using json-server, I encountered an issue with passing a query. When utilizing _expand, I am able to display the parameters of a relationship, but it doesn't seem to work when the relationship is nested within a child. ...

Data values that have been chosen and converted into JSON format

Within my PHP code, I am using two separate foreach() loops to retrieve data from MySQL databases. foreach ($result as $val) { $country = $val["count"]; //successfully fetched results $number = $val["tel"]; } foreach ($rslt as $dta) { $score = $ ...

Issues arising from parsing JSON with JQuery

The Json data below is causing a parse error in JQuery: [{"label":"75001","value":"75001"}, {"label":"75002","value":"75002"}, {"label":"75003","value":"75003"}, {"label":"75004","value":"75004"}, {"label":"75005","value":"75005"}, {"label":"75006","value ...

What steps can be taken to establish an array type that is limited to predefined values?

I am currently working on defining a type for an array that requires specific values to be present in a certain order at the beginning of the array. type SpecificArray = ('hello'|'goodbye'|string)[] // Current const myArray: SpecificAr ...

Transform PHP array to JSON object using UTF-8 encoding

Here is the PHP code I am using to retrieve data from a MySQL database with Unicode entries: $conn = mysqli_connect("localhost", "root", "", "mapping") or die ("Error".mysqli_error($conn)); mysqli_set_charset($conn,"utf8"); $sql = "select * from villages" ...

Sending JSON data object to a server in iOS7: A step-by-step guide

Hey there, I've been working on an application where I stored data in a local sqlite3 database. Now, my task is to transfer this data from the local database to an online server. To achieve this, I used a dataDictionary for retrieving all the data fro ...

The various types of Angular 2 FormBuilders

As I delved into learning Angular 2, I initially came across ngModel, and later discovered FormGroup/FormBuilder which seemed more suitable for handling complex forms. However, one downside that caught my attention was that by using FormBuilder, we sacrifi ...

Eliminate brackets from JSON string

Upon extracting a string from a JSON response: NSString *messageFromResponse = [NSString stringWithFormat:@"%@",[[JSON objectForKey:@"Response"]valueForKey:@"Message"]]; NSLog(@"<%@>", messageFromResponse); The extracted string appears as follows ...

Determine if a property of an object is an empty string in React Native

I am facing a situation where I have an object that may or may not have an image URL. { id: 1, term: "Research", imageURL: "", definition: "is a way of thinking and understanding various aspects of a procedure ...

A step-by-step guide on generating a single chip using the same word in Angular

I'm trying to find a solution to ensure that only one chip is created from the same word inputted, instead of generating duplicates. Currently, users can input variations such as "apple," "APPLE," "apPPle," "aPpLe," and I want to automatically conver ...

Is it possible to modify the styling of a different div using a fade effect during a CSS hover event?

Is it possible to achieve a smooth transition effect for changing the background image on hover of a button using the code below? $(function() { $('#a').hover(function() { $('.contenitoreindex').css('background&a ...