
Alright ladies and gents, this week I am covering fetch requests within a JavaScript/React app!
So what is a fetch request? Most simply put, a fetch request allows us to communicate with the database. It allows us to make requests to the database server without reloading the page, and then work with the data that we receive back. It is a way to load additional data after information is already presented to the user.
Syntax:

this syntax of:
fetch('url')
.then(resp => resp.json())
.then(data => ... )
never changes; the second .then()
is where we will actually do something with the data that we have received back to manipulate the DOM.
So let’s break this down into what is actually going on here.
fetch(‘url')
returns an object that represents what the data source has sent back. It does not return the actual content..then(resp => resp.json())
this method is called on the object returned from our fetch request. It takes a function that receives the response as its argument, and inside that function, we do whatever processing we need (usually.json()
), so that it can be returned and used inside of our next callback function in the second.then()
..then(data => console.log(data))
the data that is returned from our first.then
can now be used to manipulate the DOM in some way; whether that is adding text to the page, or updating something that is already there, etc.
So let’s see an example:

Here our requests are being called within the component lifecycle method componentDidMount()
. With both requests, we are reaching out to our server at the URLs http://localhost:3001/about_mes
and http://localhost:3001/projects
, then taking the object we receive back and turning it into a JSON object, and finally setting our state to include the data that was received so that we can call on it later somewhere else in our app.
This causes an update to our page with the remote data that is now stored in our state, which causes our page to re-render with our newly fetched data!