This guide will teach you how to call any REST API from a React application created with the Create React App package. If you already have an existing API that you want to call from your application, you can skip the first step, in which we will create a fake REST API using Mockoon.
When working on your React application, you may need to mock an API that is still under development, or that is only partially available. The easiest way to start working without having to wait is to create a mock API using a tool like Mockoon. (Read more about the benefits of API mocking).
To learn more about how to set up your first mock API with Mockoon, head over to the Getting started tutorial.
For the rest of the tutorial, we will use an array of fake blog posts with a single title. In Mockoon, create a
GET /posts API endpoint that returns an array of blog posts:
You can use the following JSON as the body returned by the endpoint:
Note that your fake mock server will be available at the following URL:
http://localhost:3000. It is the URL we will need to use in our React component.
After creating a mock REST API endpoint in Mockoon, you can now call it from your React component.
To do so, we need to use an AJAX library or the browser's built-in
window.fetch function. We will be using the
fetch function as it is available in most browsers.
You will find below the minimal code needed to call our API endpoint with the
We need to integrate this code into a React component. We will reuse the
App component which was automatically created by Create React App. However, we need to wrap this piece of code in a
useEffect function in order to refresh the UI when our blog posts are fetched:
Note that we also stored the call result (our blog posts) in a state called
We can now render our blog posts on the page as
<li> using a simple
Putting all this code together, we get a fully functional component loading asynchronous mock data: