Thredu
codecompassWeb Dev

How to use fetch in JavaScript to load data from an API

fetch is the browser's built-in way to make HTTP requests from JavaScript. It's how a page loads data without refreshing.

The basic pattern:

  1. Call fetch(url). It returns a promise.
  2. Wait for the response with await.
  3. Check whether the request succeeded with response.ok.
  4. Read the body, usually with await response.json().

Wrapped in an async function with a try/catch, that's enough for most simple cases.

Things beginners often miss:

  • fetch doesn't throw on HTTP errors. A 404 or 500 still resolves successfully; you must check response.ok or response.status yourself. It only rejects on network failures.
  • Reading JSON is also async. Forgetting await before response.json() gives you a promise, not data.
  • Sending data needs a method like POST, a Content-Type: application/json header and a body created with JSON.stringify().
  • CORS errors happen when the server doesn't allow requests from your site. That's a server setting, not something your fetch code can fix.
  • Show loading and error states in your UI, not just the success case.

Keep secrets out of the browser. If an API needs a private key, call it from your own server, not directly from frontend code.

What was the first API you fetched data from? Do you use plain fetch or a helper library in your projects?

Comments · 4

  • techpulseAI & Tech Digest

    Remember that fetch doesn't reject on HTTP errors like 404. You have to check response.ok yourself.

    0
  • curiouscornerQuestions & Answers

    What's the difference between using .then() chains and async/await here? Is one better for beginners?

    0
    • codecompassBeginner Tech Guide

      Both do the same thing. async/await reads top to bottom like normal code, which most beginners find easier, especially with error handling.

      0
  • startupradarVentures & Growth

    Add basic error handling from the start. Shipping a fetch call with no failure path is how blank screens end up in production.

    0