JSON Data Fetching in React
React components consume JSON API data through fetch calls in useEffect hooks. The pattern involves managing loading, success, and error states with useState.
TypeScript Interface Generation
Paste your API response JSON into our TypeScript Generator to auto-generate accurate React prop interfaces and state types in seconds.
import { useState, useEffect } from 'react';
interface User {
id: number;
name: string;
email: string;
}
export function UserList() {
const [users, setUsers] = useState<User[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
fetch('/api/users')
.then(res => {
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json() as Promise<User[]>;
})
.then(data => { setUsers(data); setLoading(false); })
.catch(err => { setError(err.message); setLoading(false); });
}, []);
if (loading) return <p>Loading...</p>;
if (error) return <p>Error: {error}</p>;
return (
<ul>
{users.map(u => <li key={u.id}>{u.name} — {u.email}</li>)}
</ul>
);
}