9️⃣ React ↔ Backend Integration

Connecting Your Frontend to Your API

Using fetch in React

fetch is built into JavaScript - no installation needed!

GET Request - Load Data

// Simple component using only useState
import { useState } from 'react';

function ProductList() {
  const [products, setProducts] = useState([]);

  // Load products when button clicked
  async function loadProducts() {
    const response = await fetch('http://localhost:3000/api/products');
    const data = await response.json();
    setProducts(data);
  }

  return (
    <div>
      <button onClick={loadProducts}>Load Products</button>
      <ul>
        {products.map(p => (
          <li key={p._id}>{p.name} - ${p.price}</li>
        ))}
      </ul>
    </div>
  );
}

POST Request - Add Data

import { useState } from 'react';

function AddProduct() {
  const [name, setName] = useState('');
  const [price, setPrice] = useState('');

  async function handleSubmit(e) {
    e.preventDefault();
    
    await fetch('http://localhost:3000/api/products', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ name, price: Number(price) })
    });
    
    alert('Product added!');
    setName('');
    setPrice('');
  }

  return (
    <form onSubmit={handleSubmit}>
      <input value={name} onChange={e => setName(e.target.value)} placeholder="Name" />
      <input value={price} onChange={e => setPrice(e.target.value)} placeholder="Price" />
      <button type="submit">Add</button>
    </form>
  );
}

DELETE Request

async function deleteProduct(id) {
  await fetch(`http://localhost:3000/api/products/${id}`, {
    method: 'DELETE'
  });
  alert('Deleted!');
}

fetch Summary

Method Code
GET fetch(url)
POST fetch(url, { method: 'POST', headers: {...}, body: JSON.stringify(data) })
PUT fetch(url, { method: 'PUT', headers: {...}, body: JSON.stringify(data) })
DELETE fetch(url, { method: 'DELETE' })

CORS - Why React Can't Connect

❌ Error: Access blocked by CORS policy

Problem: Browser blocks requests between different ports.

Solution: Add cors middleware to Express!

# Install cors
npm install cors
// Add to your Express server
const cors = require('cors');
app.use(cors());  // Now React can connect!
🎯 Key Takeaways:
  • Use fetch() to connect React to your API
  • GET = fetch(url)
  • POST/PUT = add method, headers, and body
  • Always add cors() to Express