How to Code an API Call with React!

ziratsu

Ustariz Enzo

Posted on December 18, 2021

How to Code an API Call with React!

Hey fellow creators

Let's code an API Call with React.
This is pretty common and you need to master it if you want to use React.

If you prefer to watch the video version, it's right here :

1. The hooks you need!

You need to import two hooks:

import {useState, useEffect} from "react";

function App(){
    return(
        <div className="app">
            <h1>React API Call</h1>
        </div>
    )
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Now create your state which will start at false since at first you don't have any data:

import {useState, useEffect} from "react";

function App(){

    const [imgURL, setImgURL] = useState(false);

    return(
        <div className="app">
            <h1>React API Call</h1>
        </div>
    )
}

export default App;
Enter fullscreen mode Exit fullscreen mode

2. Fetch an API

Find a random image API and do a fetch when the component is mounted, using the hook useEffect().

Let's start by simply logging the response of the fetch to check if it's working:

useEffect(() => {
    fetch('https://source.unsplash.com/random/600x800')
    .then(res => console.log(res))
}, [])
Enter fullscreen mode Exit fullscreen mode

It will be triggered after the first render of the component!

Since the response is not JSON, you don't need to parse it, you can just extract the URL from it.

useEffect(() => {
    fetch('https://source.unsplash.com/random/600x800')
    .then(res => setImgURL(res.url))
}, [])
Enter fullscreen mode Exit fullscreen mode

Now you can add the image to your JSX:

return(
        <div className="app">
            <h1>React API Call</h1>
            {imgURL && <img src={imgURL} />}
        </div>
    )
Enter fullscreen mode Exit fullscreen mode

You're using the short circuit operator, meaning that it'll only render the image if imgUrl is true.

If you refresh the page, you'll see that you have a different image each time!

This is how you can do a pretty basic API call with React!

Come and take a look at my Youtube channel: https://www.youtube.com/c/TheWebSchool

See you soon!

Enzo.

💖 💪 🙅 🚩
ziratsu
Ustariz Enzo

Posted on December 18, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related