DEV Community

Shivansh Agrawal
Shivansh Agrawal

Posted on

Use props and also fetch Data from an API in Next.js with Typescript

First, we will create a Next.js app.

Image description

You can see the response of the API by browsing https://www.thecocktaildb.com/api/json/v1/1/filter.php?c=Cocktail this link in the browser. Since we can use get request apis in the browser. to view JSON beautifully we can use JSON Viewer Pro extension.

Image description

In app/Page.tsx which displays as the First screen with path name ‘/’

To get Data from an API we will use the fetchdetails() function.

async function fetchdetails() {
  const response = await fetch(
    "https://www.thecocktaildb.com/api/json/v1/1/filter.php?c=Cocktail"
  );
  if (response.ok) {
    const responseBody = await response.json();
    // console.log(`data ${data}`);
    // setData(responseBody);
    console.log(`data ${responseBody}`);
    return responseBody;
  }
}
Enter fullscreen mode Exit fullscreen mode

This fetch details will return response.json() if the response.ok.

Then in the primary function of Page.tsx we will call this function like this :

const data = await fetchdetails();
Enter fullscreen mode Exit fullscreen mode

Props are basically used to pass data from one function to another function.

To use Props with type script. First, make an interface of data that has to pass. In my case, the interface looks like this

interface Props {
    key: String;
    strDrink: String;
    strDrinkThumb: String;
    idDrink: String;
  }
Enter fullscreen mode Exit fullscreen mode

To display data. We will create a container with an image and text to display the image and the name of the cocktail coming from the API.

Create a Components Folder in your dir and make a CocktailContainer.tsx file inside it.

// import Link from "next/link";
import Image from "next/image";
interface Props {
  strDrink: String;
  strDrinkThumb: String;
  idDrink: String;
}

export default function CocktailContainer({
  strDrink,
  strDrinkThumb,
  idDrink,
}: Props) {
  return (
    <div>
      <h1>{strDrink}</h1>
      <Image src={strDrinkThumb + ""} alt="" width={150} height={150} />
      {/* <Link href={`/asd`}></Link> */}
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Now coming back to page.tsx file we pass data from the api to the above function to display the data.

return (
    <main className="font-poppins mx-10">
      <div className="grid gap-10 grid-cols-fluid"></div>
      {data.drinks.map(function (item: Props) {
        return (
          <CocktailContainer
            key={item.idDrink.toString()}
            strDrink={item.strDrink}
            strDrinkThumb={item.strDrinkThumb}
            idDrink={item.idDrink}
          ></CocktailContainer>
        );
      })}
    </main>
Enter fullscreen mode Exit fullscreen mode

The above code uses the map to pass or display any Object or list.
The Whole code page.tsx will look like this

import Image from "next/image";
import CocktailContainer from "@/components/cocktailContainer";
async function fetchdetails() {
  const response = await fetch(
    "https://www.thecocktaildb.com/api/json/v1/1/filter.php?c=Cocktail"
  );
  if (response.ok) {
    const responseBody = await response.json();
    // console.log(`data ${data}`);
    // setData(responseBody);
    console.log(`data ${responseBody}`);
    return responseBody;
  }
}
// eslint-disable-next-line @next/next/no-async-client-component
export default async function Home() {
  const data = await fetchdetails();

  interface Props {
    key: String;
    strDrink: String;
    strDrinkThumb: String;
    idDrink: String;
  }

  return (
    <main className="font-poppins mx-10">
      <div className=""></div>
      {data.drinks.map(function (item: Props) {
        return (
          <CocktailContainer
            key={item.idDrink.toString()}
            strDrink={item.strDrink}
            strDrinkThumb={item.strDrinkThumb}
            idDrink={item.idDrink}
          ></CocktailContainer>
        );
      })}
    </main>
  );
}
Enter fullscreen mode Exit fullscreen mode

Since to use external image domains, we first configure them.

So, to do so replace this code in your next.config.js file.

/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
  images: {
    domains: ["www.thecocktaildb.com"],
  },
};

module.exports = nextConfig;
Enter fullscreen mode Exit fullscreen mode

Now after running your app, you would be seeing a list of cocktails.

Image description

Top comments (0)