React: How to Fetch Data From API
Published: 2022-03-26 03:57:42

When making user interfaces, we often need to fetch data from an API. For example, in an e-commerce site, the products will be fetched from an API, the data we fetch will include product images, prices, names, comments, etc.

In this article, I’ll cover how to fetch data from an API. I’ll build a very basic app where I fetch harry potter characters from an API, so let’s jump right into it.
**1-Create the base of our App**
Basically what we want is to show random Harry Potter characters when the page is loaded. So, let’s build a skeleton app for that.

Create a react app with create-react-app and create a Character component :

_src/Character.js_

```
import React from 'react';
import styled from 'styled-components';

const Character = ({
    imageURL,
    name
}) => {
    return (
        <Wrapper>
            <Image src={imageURL} />
            <Text>{name}</Text>
        </Wrapper>
    )
}

const Wrapper = styled.div`
border-radius:1rem;
padding:1rem;
border:2px solid black;
display:flex;
flex-flow:column nowrap;
width:20rem;
height:20rem;

`
const Image = styled.img`
width:auto;
height:85%;
object-fit:contain;
`

const Text = styled.div`
padding:0.5rem;
font-size:1.25rem;
`
export default Character

```
In this project, I’ve used styled components for styling, to learn more about them, checkout : https://smilepk145.medium.com/how-to-use-styled-components-in-react-ed609c49a6d6

And to try out our Character component, go to App.js and modify it like this :

src/App.js
We’ve used mock data to try out the Character component and the output is this:
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ywvevh4mneq8tmeuo1n8.png)
 
I think it’s good enough for our example project. So, let’s try to fetch some characters from an API and create characters dynamically.

2-Fetch data from an API

For fetching data, you can use many alternative libraries. My choice is using axios library. It’s the most popular library for fetching data. To install axios, put the below code into the terminal:

```
npm install axios
```
And after installing axios modify App.js file like below:

src/App.js

```
import React, { useEffect } from 'react';
import styled from 'styled-components';
import axios from 'axios';

const App = () => {
  useEffect(() => {
    const getCharacters = async function () {
      const baseURL = "<http://hp-api.herokuapp.com/api/characters>";
      const response = await axios.get(baseURL);
      const data = response.data;
      console.log("data", data);
    }
    getCharacters();
  }, [])

  return (
    <AppWrapper>

    </AppWrapper>
  )
}
const AppWrapper = styled.div`
width:100%;
height:100%;
display:flex;
flex-flow:row wrap;
justify-content:space-evenly;
align-items:center;
`

export default App

```

Basically, we used` useEffect` hook to fetch data when the app first loads.

In** getCharacters** function, we sent a get request to API using baseURL. And then the API returns a response. **console.log(”data”,data)’**s output is like below:
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y7xs4mdo5ybtzlutrlep.png)
 
As you can see, the data is an array of objects, each object has information about a **character**. Let’s try to show 4 random characters with our Character component. Modify the `App.js` like below:

src/App.js

```
import React, { useEffect, useState } from 'react';
import styled from 'styled-components';
import axios from 'axios';
import Character from './Character';

const App = () => {
  const [characters, setCharacters] = useState([]);
  useEffect(() => {
    const getCharacters = async function () {
      const baseURL = "<http://hp-api.herokuapp.com/api/characters>";
      const response = await axios.get(baseURL);
			/*filter the data this time, because some data doesn't have image and we
			need an image for each character*/
      const data = response.data.filter(char => char.image);
      console.log("data", data);
      let fourRandomCharacters = [];
      for (let i = 0; i < 4; i++) {
        const index = Math.floor(Math.random() * data.length);
        fourRandomCharacters.push(data[index]);
      }
			//set characters to characters state
      setCharacters(fourRandomCharacters);
    }
    getCharacters();
  }, [])

  return (
    <AppWrapper>
      {characters.map((character, index) =>
        <Character
          key={index}
          imageURL={character.image}
          name={character.name}
        />
      )}
    </AppWrapper>
  )
}
const AppWrapper = styled.div`
width:100%;
height:100%;
display:flex;
flex-flow:row wrap;
justify-content:space-evenly;
align-items:center;
`
export default App
```

This time we filtered the returned data because some data doesn’t have images. After that, we stored the 4 characters in a React state using useState hook. And we used Array.map method to render all 4 characters from state.

And the output looks like this:
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hjomzuvh9zregg12zuo9.png)
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i0cvqky64nb8yddhnfj8.png)
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/horhew2y5erldmgonke9.png)
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nzox8rzi1s832rchy6n2.png)
    


Summary:

When fetching data from an API in React, we send a get request to the API, modify the returned data according to our needs and use that data in our app.

This is it for this article, I hope you enjoyed and learned a lot.