How to Fetch data from an API in React

Clare Mburu
2 min readJul 12, 2021

Fetching data from an API can be done in so many ways. In this tutorial, we will use the Fetch API to fetch data from an external API. Fetch is a promise-based inbuilt browser API that is used to make HTTP requests from endpoints.

For this tutorial, we will fetch data from this URL and list it in a simple table. You can as well use your JSON API that you can connect to to fetch data.

This tutorial assumes that you have prior knowledge in React Hooks, UseEffect lifecycle method, promises, APIs and handling events in Javascript. All the code will be provided on Github.

Lets jump in!

When the component mounts

This involves sending a http request to an api then displaying the data to a browser. We will handle the loading state before the data is fetched in our API.

When our component mounts, we need to know whether we’ve fetched the data or we’ve completed fetching data. We will set the default loading state to false. We will show some loading indicator and then fetch the data using the useEffect hook.

When useEffect is called, we get the data from the response and then we update the state. The data will render twice. Once for the initial loading state, then a second time with the new posts data.

Handling Events

The response will be in JSON format. We will create two tables where one will render the posts data while the other will render the comments of the posts.

In order to display the posts in a table, we will need to filter the posts data based on a specific user Id. This means that when we click the user id, it should create a new table that shows the posts of that user.

For the comments table, we will need to filter the comments data based on a specific posts id. This means that when we click the post id, it should create a new table that shows comments of that post.

Conclusion

Fetch will allows us to make the http requests to get data from an endpoint. It renders first by saying loading. When the useEffect gets called , we fetch the data from the endpoint, we get the data from response and then we update the state.

React offers multiple ways to fetch data from an API. I hope I shed some light on how to effectively fetch data from an external API using the fetch API.

Thank you for reading my blog. Want to share some thoughts? Feel free to reach out to me via LinkedIn and Twitter.

--

--

Clare Mburu

I am a passionate front end developer with over 3 years of experience building responsive websites with a focus on React, Node, Mongo and Express.