Networking with fetch / axios

June 02, 2026 1 min read

Use the built-in fetch or the axios library to call APIs.

async function getProducts() {
  try {
    const res = await fetch('https://api.example.com/products');
    if (!res.ok) throw new Error('Request failed');
    return await res.json();
  } catch (e) {
    console.warn(e);
    return [];
  }
}

Wire it into a screen

const [items, setItems] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
  getProducts().then(d => { setItems(d); setLoading(false); });
}, []);
Tip: Always render three states: loading, error, and data. Users hate blank screens.

Summary

Fetch data with fetch/axios inside useEffect, store it in state, and handle loading and error states explicitly.