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://upmostly.com/tutorials/how-to-use-styled-components-in-react

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:

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:

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:

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.

Avatar photo
👋 Hey, I'm Osman Armut
Hi, I'm Osman Armut. I'm a self taught frontend developer that has a great passion for Javascript and React ecosystem. I use articles in my personal learning journey and I like to share my knowledge to help people.

💬 Leave a comment

Your email address will not be published. Required fields are marked *

We will never share your email with anyone else.