Get data from an API in React

In this article, I’ll show how to make a request to an API to get data and then display it in a React component.

This can be broken down into three steps:

  1. Initialize two state variables with useState(): one for the data, one for errors.
  2. Make the API request with axios in useEffect() and set the state variables.
  3. Display the state variables.

Here’s a working code example of how to do this:

import { useEffect, useState} from 'react'
import axios from 'axios'

function App() {
  //Step 1 - Get state variables to populate from the API
  const [recipes, setRecipes] = useState(null)
  const [error, setError] = useState(null)

  //Step 2 - Call API and set the state variables
  useEffect(() => {
    async function getRecipeData() {
      try{
        const json = await axios.get('https://localhost:7255/Recipes');
        setRecipes(json.data);
      }
      catch(err){
        setError(err);
      }   
    }

    getRecipeData()
  }, [])

  //Step 3 - Display data from state variables
  if (error){
    return <>{error.message}</>
  }
  else if (!recipes){
    return <>Loading recipes...</>
  }
  else{
    return (
    <ul>
      {recipes.map(r => (<li key={r.id}>{r.name}</li>))}
    </ul>)
  }
}
Code language: JavaScript (javascript)

Note: Install the axios package with ‘npm install axios’. If you prefer to use fetch() instead, see examples in this article about using fetch() to make web API requests.

When this first renders, it’ll show “Loading recipes…”. Then when the request succeeds, it’ll re-render and show the list of recipe names:

  • Aloo Gobi
  • Arroz con calamares
  • Baked meatballs

Note: These are actual recipes I make!

Errors

When you await axios.get(), it’ll throw an exception when the request fails (due to a network issue, CORS, etc…) and when the API returns an error response (non-OK status code).

For example, if the API is unreachable, you’ll get a generic “Network Error” error message. Check the console for more details about the error.

When the API returns an error response, you’ll get an error message containing the status code:

Request failed with status code 400Code language: plaintext (plaintext)

Why does the request fire twice?

You may have noticed that the request fires twice. This is because when you use strict mode, React renders your components twice when you’re using a dev build (hence, it’s sending the request twice):

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
    <React.StrictMode>
        <App />
    </React.StrictMode>
);

Code language: JavaScript (javascript)

If you don’t want this behavior, remove <React.StrictMode>. That’ll stop it from sending the request twice.

Leave a Comment