Using the effect hook with fetch
In this section, we will create a page that lists the blog posts returned from the REST API we just created. We will use the browser’s fetch
function and React’s useEffect
hook to interact with the REST API.
Getting blog posts using fetch
We will start by creating a function that gets blog posts from the REST API using the browser’s fetch
function; we will store the API URL in an environment variable. To do this, carry out the following steps:
- The same URL will be used to get, as well as save, new blog posts to the REST API. We will store this URL in an environment variable. So, create a file called
.env
in the root of the project containing this variable, as follows:REACT_APP_API_URL = http://localhost:3001/posts/
This environment variable is injected into the code at build time and can be accessed by code using process.env.REACT_APP_API_URL
. Environment variables in Create React App projects must be prefixed...