</>
Skip to content
React lessons (28/47)

React — API Calls

Basic Fetch

function UserList() {
    const [users, setUsers] = useState([]);

    useEffect(() => {
        fetch('https://api.example.com/users')
            .then(response => response.json())
            .then(data => setUsers(data));
    }, []);

    return (
        <ul>
            {users.map(user => (
                <li key={user.id}>{user.name}</li>
            ))}
        </ul>
    );
}

Fetch with Loading State

function UserProfile({ userId }) {
    const [user, setUser] = useState(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);

    useEffect(() => {
        fetchUser(userId)
            .then(data => {
                setUser(data);
                setLoading(false);
            })
            .catch(err => {
                setError(err);
                setLoading(false);
            });
    }, [userId]);

    if (loading) return <p>Loading...</p>;
    if (error) return <p>Error: {error.message}</p>;

    return (
        <div>
            <h2>{user.name}</h2>
            <p>{user.email}</p>
        </div>
    );
}

Post Request

function CreateUser() {
    const [name, setName] = useState('');
    const [email, setEmail] = useState('');

    const handleSubmit = async (e) => {
        e.preventDefault();

        const response = await fetch('https://api.example.com/users', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ name, email }),
        });

        const data = await response.json();
        console.log('Created:', data);
    };

    return (
        <form onSubmit={handleSubmit}>
            <input value={name} onChange={(e) => setName(e.target.value)} />
            <input value={email} onChange={(e) => setEmail(e.target.value)} />
            <button type="submit">Create User</button>
        </form>
    );
}

API Call Examples

// Custom hook for API calls
function useApi(url) {
    const [data, setData] = useState(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);

    useEffect(() => {
        const fetchData = async () => {
            try {
                const response = await fetch(url);
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                const json = await response.json();
                setData(json);
            } catch (err) {
                setError(err);
            } finally {
                setLoading(false);
            }
        };

        fetchData();
    }, [url]);

    return { data, loading, error };
}

// Usage
function ProductList() {
    const { data, loading, error } = useApi('/api/products');

    if (loading) return <p>Loading...</p>;
    if (error) return <p>Error: {error.message}</p>;

    return (
        <div>
            {data.map(product => (
                <div key={product.id}>{product.name}</div>
            ))}
        </div>
    );
}

// With authentication
function AuthenticatedFetch() {
    const fetchData = async () => {
        const token = localStorage.getItem('token');

        const response = await fetch('/api/protected', {
            headers: {
                'Authorization': `Bearer ${token}`,
            },
        });

        return response.json();
    };

    return <button onClick={fetchData}>Fetch Protected Data</button>;
}

Mini Practice

Write React code that:

  1. Makes a basic GET request
  2. Handles loading and error states
  3. Makes a POST request
  4. Creates a custom hook for API calls

Up Next

Next: Learn about Fetch.

Related Topics

Frequently Asked Questions about API Calls

What is API Calls in React?

API Calls is a fundamental concept in React. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn API Calls?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn API Calls.

Why is API Calls important in React?

API Calls is essential for React development. Understanding this concept will help you write better code and solve real-world problems more effectively.