Loading

Quipoin Menu

Learn • Practice • Grow

react / Fetch API in React
tutorial

Fetch API in React

In real-world applications, you need to communicate with servers fetching data, submitting forms, or updating information. JavaScript provides a built-in method called `fetch()` for making HTTP requests. In React, we typically use `fetch` inside `useEffect` to load data when components mount.

What is the Fetch API?

The Fetch API is a modern JavaScript interface for making HTTP requests. It returns a Promise that resolves to the Response object representing the response to the request.

Think of `fetch` as a messenger you send to a server. The messenger goes, gets the data, and brings it back to your app.

Basic Syntax
fetch(url)
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));

Using Fetch in React
import React, { useState, useEffect } from 'react';

function UserList() {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/users')
      .then(response => {
        if (!response.ok) {
          throw new Error('Network response was not ok');
        }
        return response.json();
      })
      .then(data => {
        setUsers(data);
        setLoading(false);
      })
      .catch(err => {
        setError(err.message);
        setLoading(false);
      });
  }, []);

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

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

POST Request with Fetch
const handleSubmit = async (userData) => {
  try {
    const response = await fetch('https://api.example.com/users', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(userData),
    });
    const data = await response.json();
    console.log('User created:', data);
  } catch (error) {
    console.error('Error:', error);
  }
};

Two Minute Drill

  • Fetch API is a built-in JavaScript method for making HTTP requests.
  • It returns a Promise, so you use `.then()` or `async/await` to handle responses.
  • Always call `response.json()` to extract the JSON body from the response.
  • In React, use `fetch` inside `useEffect` for data fetching when components mount.
  • Handle loading and error states for better user experience.

Need more clarification?

Drop us an email at career@quipoinfotech.com