Navigating images within Typescript - NextJS operations

My website fetches data from the Spoonacular API to search for ingredients, receiving responses with titles and images. I have defined the types as:

export interface IProps {
    id: number;
    name: string;
    image: string;
  }

Currently, my list of ingredients is structured like this:

const List = (props: { ingredient: IProps }) => {
  const { ingredient } = props;

  return (
    <Container>
      <Box>
        <Image src={ingredient.image} alt={ingredient.name} />
        <Box>
          {ingredient.name}
        </Box>
      </Box>
    </Container>
  );
};

export default List;

I have omitted all styling information above.

The props are passed from where I make the call:

const Search = () => {


  const [ingredients, setIngredients] = useState<IProps[]>([]);
  const [value, setValue] = useState("");

  const handleSubmit = (e) => {
    e.preventDefault();

    axios
      .get(
        `https://api.spoonacular.com/food/ingredients/search?query=${value}&number=2&apiKey=${URL}`
      )
      .then((res) => res.data)
      .then((data) => data.results)
      .then((data) => setData(data))
      .catch((err) => console.log(err));
  };

  const handleChange = (e) => {
    setValue(e.target.value);
  };

  return (
    <Flex justifyContent="center">
      <Flex direction="column">
        <Heading mb={6}>Search Recipe</Heading>
        <Input
          onChange={handleChange}
          value={value}
          name="search"
          id="search"
          placeholder="Write here..."
          variant="filled"
          mb={2}
          type="text"
        />
        <Button onClick={handleSubmit} mb={5}>
          Search
        </Button>
       
      </Flex>
      {ingredients.map((ingredient) => (
        <List key={ingredient.id} ingredient={ingredient} />
      ))}
    </Flex>
  );
};
export default Search;

However, I am puzzled by the fact that I receive a 404 error for the image:

Request URL: http://localhost:3000/lemon.png
Request Method: GET
Status Code: 404 Not Found
Remote Address: 000.0.0.0:0000
Referrer Policy: strict-origin-when-cross-origin

As I am new to TypeScript, I may have overlooked something fundamental?

Answer №1

When retrieving data from the API, you may encounter a situation where only a filename such as lemon.png is provided. In order to access the corresponding image, it is necessary to concatenate this filename with the base URL

https://spoonacular.com/cdn/ingredients_100x100/
before utilizing it within the Image component. For example, the complete URL would be
https://spoonacular.com/cdn/ingredients_100x100/lemon.png
.

To learn more about fetching images from the API, refer to the documentation available at (link to Spoonacular API docs)

Answer №2

Expanding on the insights shared by Ritik Mishra, here is an illustration for you and fellow Spoonacular users regarding how your src should appear:

src={`https://spoonacular.com/cdn/ingredients_250x250/${ingredient.image}`}

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

What is the ideal configuration for Typescript within ASP.NET 4 MVC 5 on Visual Studio 2015?

Currently, I am in the process of integrating a TypeScript project into a VS2015 MVC 5 project (which is based on ASP.NET 4, specifically not asp.net 5 or asp.net 6 - only the MVC portion is version 5). All aspects of my query pertain solely to this target ...

TypeScript error: 'IteratorResult' is declared multiple times

When attempting to compile using tsc (which is installed globally), I encountered an error: ~/AppData/Roaming/nvm/v11.15.0/node_modules/typescript/lib/lib.es2015.iterable.d.ts:41:6 - error TS2300: Duplicate identifier 'IteratorResult'. 41 type ...

Is it possible to update the text within a button when hovering over it in Angular?

https://i.sstatic.net/ZhNeM.png https://i.sstatic.net/kb670.png I'm looking to update the text displayed inside a button when hovering over it, similar to the examples in these images. I have already implemented the active state, but now I just need ...

The Next.js API is indicating that the API request was resolved without a response being sent, however, I am confident that I

After creating a basic page and API for uploading a CSV file, I encountered an issue. The file uploads successfully and gets saved on the server through the API, but an error message pops up: API resolved without sending a response for /api/uploadv2, this ...

Issues with APIs surfaced following the transition from DataGridPro to DataGridPremium

In my current project, we initially implemented the MUI X DataGrid but later switched to DataGridPro due to business requirements. Recently, we upgraded our plan from Pro to Premium which has caused some unexpected issues in our existing code. I am using " ...

Adding 30 Days to a Date in Typescript

Discovering Typescript for the first time, I'm attempting to calculate a date that is (X) months or days from now and format it as newDate below... When trying to add one month: const dateObj = new Date(); const month = dateObj.getUTCMonth() + 2; con ...

Guide to employing Axios types in project declaration files

When working on my project's type declaration file, I encountered a dilemma with using Axios types as part of my own types. The issue lies in the fact that all declarations for Axios are exported from their official repository. I specifically need to ...

utilizing regular expressions in TypeScript

I'm currently working with Angular 2 and I have a URL link: www.abcd.com/Computers_Accessories/panache-air-pc/P-coac-20620024815-cat-z.html#newId=P-coac-41130779424?trackId=paym&subTrackId=&infitag=1234 My goal is to remove the portion #newId ...

Uncertainty regarding the integration process of `create-react-app --template typescript` with typescript-eslint

After creating a react project using npx create-react-app my-app --template typescript, I was surprised to find that typescript-eslint was already enabled by default. https://i.sstatic.net/1uijf.png Upon inspecting the eslint config within the package.jso ...

Experiencing "localhost redirect loop due to NextJS Middleware" error

After successfully integrating email/password authentication to my locally hosted NextJS app using NextAuth, I encountered an issue with the middleware I created to secure routes. Every time I tried to sign out, I received an error stating "localhost redir ...

Encountered an error stating 'name' property is undefined while using @input in Angular 2

Everything seems to be set up correctly, but I'm encountering an error in the browser console that says "Cannot read property 'name' of undefined": https://i.sstatic.net/TvfEr.png This is how my media.component.ts file is structured: impo ...

Encountering an issue: Next.js application with Sendgrid API requiring an array for `personalizations`

I am encountering an issue with my sendAlerts.js file in the api folder. Every time I try to run it, I receive the Error: Array expected for personalizations at http://localhost:3000/api/sendAlerts This is the code inside api/sendAlerts: const mail = requ ...

Has a fresh iteration of the contextualCard functionality been introduced in faker.js?

I'm trying to enhance my knowledge of faker after a system reset, and I'm curious about its latest features. Does the new version include a function similar to contextual cards or a way to generate fake usernames? Here's a snippet of my curr ...

When restarting the React application, CSS styles disappear from the page

While developing my React application, I encountered a problem with the CSS styling of the Select component from Material UI. Specifically, when I attempt to remove padding from the Select component, the padding is successfully removed. However, upon refre ...

Ensuring a Fixed Delta Tooltip in lightweight-charts is essential for maintaining a seamless

I have implemented lightweight-charts to present a chart using mock data. I am looking to establish a fixed Delta Tooltip on the chart when the page loads, with predetermined start and end dates that are specified as input. Furthermore, I aim to restrict t ...

I'm struggling to figure out how to specify the data type for storing an array of objects in a variable using React.useState

I am currently working on extracting values from an .xlsx file using the SheetJS library. Below, I will provide the code snippets, errors encountered, and the different approaches I have attempted. Data extracted from var dataToJson: (6) [{…}, {…}, { ...

The for loop finishes execution before the Observable in Angular emits its values

I am currently using a function called syncOnRoute() that returns a Promise. This function is responsible for synchronizing my data to the API multiple times based on the length of the data, and it returns a string message each time. However, I am facing a ...

I'm having trouble getting Mapbox to function properly within my Next.js application

I've been struggling with implementing the react-map-gl library without success. I followed the instructions in the documentation at https://docs.mapbox.com/mapbox-gl-js/guides/, but unfortunately, it's not working for me. Here is the code I&apos ...

The Typescript loop appears to be stuck and not moving through the

I have encountered a problem while trying to iterate through my array using foreach and forloop in an angular 8 application. Despite having 250 objects in the array, it is not iterating through any elements. I am unable to figure out what the issue could b ...

What are the steps for integrating angular2 starter with express?

Can someone explain how to integrate the following Angular starter template into an Express framework? https://github.com/gdi2290/angular-starter I am able to start the webpack dev server without any issues, but I would like to utilize additional librari ...