Fetching Data With React Hooks and Fetch API [Beginners Guide]
Tags: javascript, react, tutorial, webdev
Published: 2020-07-09 12:25:05

Although I don’t like sharing food, I’m okay with sharing knowledge, so today I’m going to talk about fetching data, using react hooks and Fetch API. :D

After a short introduction and getting you familiar with those terms, I’m also going to show you how to use them in code. How exactly? By giving you examples and walking you through the process step by step.

So bare with me and let’s go! 


![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/9my3zhb387xhl00iunil.gif)


##Fetch API


<strong>Fetch API</strong> is a promise-based JS API, used for making asynchronous HTTP requests in a browser similar to XMLHttpRequest. It's standardized and supported by all modern browsers, except for IE.
In case IE needs to be covered as well, then there's a polyfill released by Github.

You can find the full documentation [here](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)

##UseState


<strong>UseState</strong> is a Hook that allows you to have state variables in functional components. It allows us to use the same capabilities that <strong>this.state</strong> provides in a class.

Full documentation is available at [this link](https://reactjs.org/docs/hooks-state.html)


##UseEffect


It executes functions after the component gets rendered.
We can think of <strong>UseEffect</strong> as componentDidMount, componentDidUpdate and componentWillUnmount combined together.

Find the full documentation [here](https://reactjs.org/docs/hooks-effect.html)


##Let’s get down to business


By now, I’m sure you have a basic understanding of what we’re going to use. That means we can slowly start diving into the code and then eventually show you the data from API.

I want to keep it as simple as possible so we’re going to use a placeholder API. You can take a look at it
[here](https://jsonplaceholder.typicode.com/posts)


##What are the prerequisites?

Since we’re keeping it simple and leaving the focus on fetching data, instead of React, we’ll just use the Create React App.
To install it, use the next commands in terminal:

```Javascript
npx create-react-app my-app
cd my-app
npm start
```

After installing the app, your folder structure should look like this:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/oylt8p6qz2dg48ru4h3x.png)

Locate yourself at App.js and voila! We’re ready to start.

##Fetching data


First, we’re going to import stuff we’re going to use and create a function.


```Javascript
import React, {useState, useEffect} from "react"

const App = () => {
  return <div> Fetched data will be displayed here</div>
}
```


The next step is to add a <strong>useState</strong> hook and to define the name of the state - in our case, that's data. Then, we define the function we’ll use later on to update the state - <strong>setData</strong>.
In the end, we set the initial value of our state, which is <strong>null</strong in our case.


```Javascript
import React, {useState, useEffect} from "react"

const App = () => {
  const [data, setData] = useState(null)
  return <div> Fetched data will be displayed here</div>
}
```

After adding our <strong>useState</strong> hook to handle the data, the next step is to make the fetch request. 

First, we’re going to create a constant <strong>fetchURL</strong>, in case we need to reuse our endpoint to fetch other data, except for posts. You can check [here](https://jsonplaceholder.typicode.com ) what else you can fetch and play with.

Then we create an arrow function named <strong>getData</strong> and inside of that function, we’re going to call <strong>fetch()</strong>.
Inside fetch, we’re going to provide a previously defined constant <strong>fetchURL</strong> and add /<strong>posts</strong>, since we’re fetching posts.


```Javascript
import React, {useState, useEffect} from "react"
const fetchURL = "https://jsonplaceholder.typicode.com"
const App = () => {
  const [data, setData] = useState(null)
  const getData = () =>
    fetch(`${fetchURL}/posts`)
      .then((res) => res.json())

  return <div> Fetched data will be displayed here</div>
}
```


After defining our request, it's time to bring in <strong>useEffect</strong>. Then we’re calling our <strong>getData()</strong> function inside of the <strong>useEffect</strong> hook to set it to the local state.

At the end of useEffect, we added an empty array [], because that way, useEffect runs only once.


```Javascript
import React, {useState, useEffect} from "react"
const fetchURL = "https://jsonplaceholder.typicode.com"
const App = () => {
  const [data, setData] = useState(null)
  const getData = () =>
    fetch(`${fetchURL}/posts`)
      .then((res) => res.json())

 useEffect(() => {
    getData().then((data) => setData(data))
  }, [])
  return <div> Fetched data will be displayed here</div>
}
```

At this point, we have everything ready to show the data inside our div. We’re going to use a map() function to iterate through this array of data.

In case you’re not familiar with the map you can read the full documentation [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map). Once we iterate over the data, we can access posts' titles, which we’re calling by <strong>item.title</strong>.


```Javascript
import React, { useEffect, useState } from 'react'

const App = () => {
  const [data, setData] = useState(null)
  const fetchURL = "https://jsonplaceholder.typicode.com"
  const getData = () =>
    fetch(`${fetchURL}/posts`)
      .then((res) => res.json())

  useEffect(() => {
    getData().then((data) => setData(data))
  }, [])

  return (
    <div>
      {data?.map((item) => 
        <ul>
          <li>{item.title}</li>
        </ul>
      )}
    </div>
  )
}

export default App;
```

If you did exactly as written in the post, your browser should, in the end, look like this:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/u2qcfqij1yo1icqpc9at.png)

##To conclude

You made it through! Congrats! Hope this guide will help you fetch data and teach you how to use react hooks for other use cases as well. 🤗 


To access the full working demo, click this [link](https://github.com/tBorbas/ReactHooksAndFetchAPI) and download it from the repo. The code in the repo is the same as it is in the article so you can follow up easier.

If you have any questions, feel free to hit me up. Happy coding!