Home About Skills Products
Work
Projects Services Experience
Learn
Tutorials Courses Blogs Resources
Contact
Tutorials · React JS

Fetching Data from an API (fetch and Axios)

Fetching Data from an API (fetch and Axios)

In real-world apps, most data comes from a backend API. The standard React pattern is: call it inside useEffect, and track three states — loading, data, and error.

With the Native fetch()

function ProductList() {
  const [products, setProducts] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    fetch('/api/products')
      .then(res => {
        if (!res.ok) throw new Error('Failed to fetch products');
        return res.json();
      })
      .then(data => setProducts(data))
      .catch(err => setError(err.message))
      .finally(() => setLoading(false));
  }, []);

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

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

With Axios (Cleaner Syntax)

npm install axios
import axios from 'axios';

useEffect(() => {
  async function loadProducts() {
    try {
      const response = await axios.get('/api/products');
      setProducts(response.data);
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  }

  loadProducts();
}, []);

Axios has a few advantages over fetch: automatic JSON parsing, automatically throwing an error on non-2xx status codes, and request/response interceptors — which is why most production apps prefer it.

Key Takeaways

  • The standard data-fetching pattern: track loading → success/error states.
  • fetch doesn't throw on non-2xx responses by default — you have to check res.ok manually.
  • Axios gives you a cleaner API and is more common in larger projects.
What is React? JSX Introduction and Your First Component

What is React? JSX Introduction and Your First Component

What problem React actually solves, how JSX syntax works, and how to build your first component.

Setting Up a React App with Vite

Setting Up a React App with Vite

Set up a modern React project in seconds with Vite, and understand the resulting folder structure.

Understanding Components and Props

Understanding Components and Props

Build functional components and pass data from parent to child components using props.

Advertisement
Esc