Data Types and the Product API

Before we display anything, we need data. We will use DummyJSON, a free fake REST API that returns realistic product data. No account or API key needed.

Define the Product type

Create src/api/types.ts:

export type Product = {
  id: number;
  title: string;
  description: string;
  price: number;
  category: string;
  rating: number;
  thumbnail: string;
  images: string[];
};

This matches the fields we will use from the DummyJSON response. The API returns more fields, but we will only select the ones we need.

Write the fetch functions

Create src/api/products.ts:

import type { Product } from "./types";

const BASE_URL = "https://dummyjson.com";

export async function fetchProducts(): Promise<Product[]> {
  const res = await fetch(
    `${BASE_URL}/products?limit=12&select=id,title,price,category,rating,thumbnail,images,description`,
  );

  if (!res.ok) {
    throw new Error("Failed to fetch products");
  }

  const data = await res.json();
  return data.products as Product[];
}

export async function fetchProduct(id: number): Promise<Product> {
  const res = await fetch(
    `${BASE_URL}/products/${id}?select=id,title,price,category,rating,thumbnail,images,description`,
  );

  if (!res.ok) {
    throw new Error(`Failed to fetch product ${id}`);
  }

  return (await res.json()) as Product;
}

There are two functions here. fetchProducts() returns a list of products, limited to 12, and fetchProduct(id) returns a single product. Both use the select query parameter to request only the fields we need.

These are plain async functions. They do not use any React hooks. We will call them from our components in the next sections.

Checkpoint: Commit your progress.

git add .
git commit -m "shopping-cart-02: Data types and API functions"
git push