No fears, my coding babies! By the end of this blog post, you'll be ready to make fetch happen!
What is Fetch?
fetch() request allows a developer to access data (or wink wink, fetch) data by sending asynchronous HTTP request to a server from a web browser and returning a promise in the form of a response, once the data is received.
Lets Send Your First
Firstly, let us invoke the
fetch() function with the URL of the desired API. And if you prefer cleaner code, initialize a variable with the API URL and pass the variable as an argument to the fetch function.
For this example, I'll be using a fake API, but you're free to use any API that meets your needs.
const baseURL = "https://jsonplaceholder.typicode.com/posts"; fetch(baseURL)
fetch() method returns a promise, we can use the
.then() to handle the response.
fetch(baseURL) .then(response => ?)
With the first promise, we need to add a
.json() method to return the resolved promise's information as JSON.
fetch(baseURL) .then(response => response.json())
Do not forget to add your parenthesis after
.json()! Like functions, if the parenthesis are omitted, there's no way the method could be invoked.
Now, it's time for our second
.then() method. Here, I'm logging the data we just received from our API in the console. The data I'm logging is the data we will be using for a deliverable we would need to meet, if there was one.
fetch(baseURL) .then(response => response.json()) .then(data => console.log(data))
The names we given to "response" and "data" are also not set in stone.
fetch(baseURL) .then(res => res.json()) .then(bakeryData => console.log(bakeryData))
A naming format like this one is just as valid as our original example. Just be sure to make the variable names match!
For readability sake, if you are going to name it something other than "data", I encourage a name that hints to what the data is in reference to.
What's Rendered in the Console
Here we have an array of objects, ready to be iterated over and rendered onto our DOM like so!
Hopefully, you can take away the knowledge I've learned and apply it to your project. If there's a step you're struggling over, take a second to re-read the code or look down below at the resources I provided, to supplement and fill in the gaps of your understanding.
Terminology You Should Know
-Asynchronous - allows another task to run before the previous one finishes.
-GET Requests — used for retrieving or “fetching” data from an API.
-POST Requests — used for uploading or adding data.
-PATCH/PUT Requests — used for editing data that is already in the database.
-DELETE Requests — used for deleting a piece of data.
MDN Fetch Documentation
MDN Promise Documentation
Free Fake API
Top comments (0)