DEV Community

Cover image for Mock an e-commerce backend for your React app in 5 minutes
Indika Gayashan
Indika Gayashan

Posted on

Mock an e-commerce backend for your React app in 5 minutes

You're building the frontend for a store. The design is ready, but the backend isn't, and you're tired of hardcoding const products = [...] in a file.

In this tutorial we'll build a small React product page against a free mock REST API, with no backend, no API key and no signup. By the end you'll have:

  • a product list with search and pagination
  • each product's category and reviews loaded in the same request
  • a "create product" form that shows real validation errors
  • a way to test your loading and error states on demand

Disclosure: I built DevSeed API, the mock API used here. It's free, and I'd love feedback on it.

1. Look at the data

Every endpoint is a plain GET you can open in the browser:

https://www.devseedapi.com/api/v1/ecommerce/products?limit=2
Enter fullscreen mode Exit fullscreen mode
{
  "success": true,
  "data": [
    { "id": "p1", "name": "Wireless Mouse", "price": 29.99, "categoryId": "c1", "createdAt": "2026-03-02T10:00:00Z" },
    { "id": "p2", "name": "Mechanical Keyboard", "price": 79.99, "categoryId": "c1", "createdAt": "2026-03-02T10:10:00Z" }
  ],
  "meta": { "total": 120, "page": 1, "limit": 2, "totalPages": 60 }
}
Enter fullscreen mode Exit fullscreen mode

The e-commerce set also has categories, reviews, orders, cart and coupons, and there are user and SaaS datasets too. Every list endpoint supports the same query params:

What Example
Pagination ?page=2&limit=10
Search ?search=mouse
Exact filter ?categoryId=c1
Range filter ?minPrice=20&maxPrice=50
Sort ?sortBy=price&order=asc
Related data ?include=category,reviews

They combine, so ?search=mouse&maxPrice=50&sortBy=price&order=asc returns the mouse-related products under $50, cheapest first.

2. Load related data in one request

This is the part most mock APIs skip. On a real product page you need the product's category and its reviews, and you don't want to fire three requests and join them yourself.

GET https://www.devseedapi.com/api/v1/ecommerce/products/p1?include=category,reviews
Enter fullscreen mode Exit fullscreen mode
{
  "success": true,
  "data": {
    "id": "p1",
    "name": "Wireless Mouse",
    "price": 29.99,
    "categoryId": "c1",
    "category": { "id": "c1", "name": "Computer Accessories" },
    "reviews": [
      { "id": 101, "productId": "p1", "userId": "u1", "rating": 5, "comment": "Excellent mouse!" },
      { "id": 163, "productId": "p1", "userId": "u70", "rating": 5, "comment": "Exactly as described." }
    ]
  }
}
Enter fullscreen mode Exit fullscreen mode

(Trimmed a little for space.) include works on list endpoints too, which is what we'll use next.

3. A product list with search and pagination

Set up a React app (npm create vite@latest shop -- --template react) and add a small hook:

// useProducts.js
import { useEffect, useState } from "react"

const API = "https://www.devseedapi.com/api/v1/ecommerce"

const LOADING = { status: "loading", products: [], meta: null, error: null }

export function useProducts({ search, page, simulate = {} }) {
  // One string describing the request; a new value means a new fetch.
  const key = JSON.stringify({ search, page, ...simulate })
  const [result, setResult] = useState({ key: null })

  useEffect(() => {
    const controller = new AbortController()
    const params = new URLSearchParams({ limit: 8, include: "category,reviews", ...JSON.parse(key) })

    fetch(`${API}/products?${params}`, { signal: controller.signal })
      .then(async res => {
        const body = await res.json()
        if (!res.ok) throw new Error(body.message ?? `HTTP ${res.status}`)
        setResult({ key, status: "success", products: body.data, meta: body.meta, error: null })
      })
      .catch(err => {
        if (err.name !== "AbortError") {
          setResult({ key, status: "error", products: [], meta: null, error: err.message })
        }
      })

    return () => controller.abort()
  }, [key])

  // Until the response for the current request arrives, we're loading.
  return result.key === key ? result : LOADING
}
Enter fullscreen mode Exit fullscreen mode

And the page:

// ProductList.jsx
import { useState } from "react"
import { useProducts } from "./useProducts"

const average = reviews =>
  reviews.length ? (reviews.reduce((sum, r) => sum + r.rating, 0) / reviews.length).toFixed(1) : "–"

export default function ProductList() {
  const [search, setSearch] = useState("")
  const [page, setPage] = useState(1)
  const { status, products, meta, error } = useProducts({ search, page })

  return (
    <div>
      <input
        placeholder="Search products"
        value={search}
        onChange={e => { setSearch(e.target.value); setPage(1) }}
      />

      {status === "loading" && <p>Loading…</p>}
      {status === "error" && <p role="alert">Couldn't load products: {error}</p>}

      <ul>
        {products.map(p => (
          <li key={p.id}>
            <strong>{p.name}</strong> · ${p.price} · {p.category?.name} · ★ {average(p.reviews)} ({p.reviews.length})
          </li>
        ))}
      </ul>

      {meta && (
        <nav>
          <button disabled={page <= 1} onClick={() => setPage(page - 1)}>Previous</button>
          <span> Page {meta.page} of {meta.totalPages} </span>
          <button disabled={page >= meta.totalPages} onClick={() => setPage(page + 1)}>Next</button>
        </nav>
      )}
    </div>
  )
}
Enter fullscreen mode Exit fullscreen mode

Each product arrives with its category and reviews already attached, so there's no second round of requests. meta.totalPages drives the pagination buttons.

4. A create form with real validation errors

Mock APIs usually accept anything you POST, so your error handling never gets exercised. Here, writes are validated like a real API but never stored: the response shows the record that would have been created.

Send a bad body:

curl -X POST https://www.devseedapi.com/api/v1/ecommerce/products \
  -H "Content-Type: application/json" \
  -d '{"name":"Desk Lamp","price":"cheap"}'
Enter fullscreen mode Exit fullscreen mode
{
  "success": false,
  "message": "Validation failed",
  "errors": [
    { "field": "price", "message": "must be a number" },
    { "field": "categoryId", "message": "is required" }
  ]
}
Enter fullscreen mode Exit fullscreen mode

That's a 422. It even checks references: "categoryId": "c999" fails with no categories record with id "c999". A valid body returns 201 with a new id and a Location header.

A form that maps those errors onto fields:

// NewProductForm.jsx
import { useState } from "react"

const API = "https://www.devseedapi.com/api/v1/ecommerce"

export default function NewProductForm() {
  const [form, setForm] = useState({ name: "", price: "", categoryId: "c1" })
  const [fieldErrors, setFieldErrors] = useState({})
  const [created, setCreated] = useState(null)

  async function handleSubmit(e) {
    e.preventDefault()
    setFieldErrors({})
    setCreated(null)

    const res = await fetch(`${API}/products`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ ...form, price: form.price === "" ? undefined : Number(form.price) }),
    })
    const body = await res.json()

    if (res.status === 422) {
      setFieldErrors(Object.fromEntries(body.errors.map(err => [err.field, err.message])))
    } else if (res.ok) {
      setCreated(body.data)
    }
  }

  const field = name => (
    <label>
      {name}
      <input value={form[name]} onChange={e => setForm({ ...form, [name]: e.target.value })} />
      {fieldErrors[name] && <small style={{ color: "crimson" }}>{fieldErrors[name]}</small>}
    </label>
  )

  return (
    <form onSubmit={handleSubmit}>
      {field("name")}
      {field("price")}
      {field("categoryId")}
      <button>Create</button>
      {created && <p>Created {created.name} with id {created.id}</p>}
    </form>
  )
}
Enter fullscreen mode Exit fullscreen mode

Leave the price empty or type a category that doesn't exist, and you'll see the server's message under the right field. PUT, PATCH and DELETE on /products/:id work the same way.

5. Test your loading and error states

The happy path is easy. The states that break in production are the slow request and the failed one, and they're hard to trigger against a real backend. Three query params do it:

Param Effect
delay=2000 waits 2 seconds before responding
error=503 always responds with that status
errorRate=30 fails 30% of requests with a 500

Our hook already passes extra params through, so:

// See the spinner for 2 seconds
useProducts({ search, page, simulate: { delay: 2000 } })

// See the error state
useProducts({ search, page, simulate: { error: 503 } })

// Flaky network: does a retry button or a stale list still look right?
useProducts({ search, page, simulate: { errorRate: 30 } })
Enter fullscreen mode Exit fullscreen mode

The error=503 case returns { "success": false, "message": "Simulated API Error" } with a 503 status, so the component shows "Couldn't load products: Simulated API Error". This is also handy for Storybook stories and Playwright/Cypress tests of your error UI.

Swapping in the real backend later

When your backend is ready, change API to point at it. If your real API uses the same ideas (page/limit, a meta object, field-level 422 errors), the components barely change. If it doesn't, the mock gives you a concrete contract to discuss with your backend team.

A few honest limits: writes are never saved, so a POST won't appear in the next GET. The data is the same for everyone, and there's a rate limit of 200 requests per 15 minutes per client.

Wrap-up

We built a product list with search, pagination and related data in a single request, a form that handles real validation errors, and a way to test loading and failure states, all against a free API with no setup.

If there's a dataset you'd want next (social media, fintech, edtech…), or something that annoyed you, tell me here. It takes under a minute, and it decides what gets built next.

Top comments (0)