DEV Community

Cover image for Fetching Data With React Hooks and Fetch API [Beginners Guide]
Tomislav Borbaš
Tomislav Borbaš

Posted on

Fetching Data With React Hooks and Fetch API [Beginners Guide]

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

Fetch API

Fetch API 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

UseState

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

Full documentation is available at this link

UseEffect

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

Find the full documentation here

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

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:

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

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

Alt Text

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.

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

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

The next step is to add a useState 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 - setData.
In the end, we set the initial value of our state, which is null</strong in our case.

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 useState hook to handle the data, the next step is to make the fetch request.

First, we’re going to create a constant fetchURL, in case we need to reuse our endpoint to fetch other data, except for posts. You can check here what else you can fetch and play with.

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

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 useEffect. Then we’re calling our getData() function inside of the useEffect 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.

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. Once we iterate over the data, we can access posts' titles, which we’re calling by item.title.

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

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 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!

Oldest comments (0)