Kayla Budzeak
2 min readMay 22, 2021
Mean Girls Gretchen Weiners That is so fetch!

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:

fetch request syntax example

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.

  1. fetch(‘url') returns an object that represents what the data source has sent back. It does not return the actual content.
  2. .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().
  3. .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:

fetch request example within an in development React app

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!

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Kayla Budzeak
Kayla Budzeak

Written by Kayla Budzeak

I'm a Full-Stack Software Engineer, with a background in customer service, who recently graduated from Flatiron School. In my down time I love to bake & garden.

No responses yet

Write a response