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

React — Fetch

Basic Fetch

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

Fetch with Options

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

// PUT request
fetch(`https://api.example.com/users/${id}`, {
    method: 'PUT',
    headers: {
        'Content-Type': 'application/json',
    },
    body: JSON.stringify({ name: 'Jane' }),
});

// DELETE request
fetch(`https://api.example.com/users/${id}`, {
    method: 'DELETE',
});

Fetch with Headers

// With authorization
fetch('https://api.example.com/protected', {
    headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json',
    },
});

// With custom headers
fetch('https://api.example.com/data', {
    headers: {
        'X-Custom-Header': 'value',
        'Accept': 'application/json',
    },
});

Error Handling

async function fetchData() {
    try {
        const response = await fetch('https://api.example.com/data');

        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }

        const data = await response.json();
        return data;
    } catch (error) {
        console.error('Fetch error:', error);
        throw error;
    }
}

Fetch Examples

// Complete data fetching component
function DataFetcher({ url }) {
    const [data, setData] = useState(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);

    useEffect(() => {
        const controller = new AbortController();

        const fetchData = async () => {
            try {
                const response = await fetch(url, {
                    signal: controller.signal,
                });

                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }

                const json = await response.json();
                setData(json);
            } catch (err) {
                if (err.name !== 'AbortError') {
                    setError(err);
                }
            } finally {
                setLoading(false);
            }
        };

        fetchData();

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

    if (loading) return <div>Loading...</div>;
    if (error) return <div>Error: {error.message}</div>;
    if (!data) return <div>No data</div>;

    return <pre>{JSON.stringify(data, null, 2)}</pre>;
}

// CRUD operations
function useCrud(baseUrl) {
    const getAll = async () => {
        const response = await fetch(baseUrl);
        return response.json();
    };

    const create = async (data) => {
        const response = await fetch(baseUrl, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(data),
        });
        return response.json();
    };

    const update = async (id, data) => {
        const response = await fetch(`${baseUrl}/${id}`, {
            method: 'PUT',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(data),
        });
        return response.json();
    };

    const remove = async (id) => {
        await fetch(`${baseUrl}/${id}`, {
            method: 'DELETE',
        });
    };

    return { getAll, create, update, remove };
}

Mini Practice

Write React code that:

  1. Makes a basic fetch request
  2. Handles different HTTP methods
  3. Adds error handling
  4. Creates a custom hook for CRUD operations

Up Next

Next: Learn about Async operations.

Related Topics

Frequently Asked Questions about Fetch

What is Fetch in React?

Fetch 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 Fetch?

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 Fetch.

Why is Fetch important in React?

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