Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
February 16, 2022 04:31 am GMT

Everything You Need To Know About .Fetch()

What is Fetch()?

We can interact with data inside of our JavaScript file pretty easily, but what about data outside of our JavaScript file? In order to interact with and manipulate data from an outside source, like an API or other server, we use Fetch().Fetch() is a method in JavaScript that allows us make a request to a server.

Using Fetch()

function getData() {    fetch(url)    .then(response => {        //function for when the response is received    })}getData()

The code above shows how you would make a GET request using Fetch(). When we make a request to a url there will be a delay that takes longer than the amount of time it would take for our code to execute. Due to that slight pause the code needs to wait while that promise is being met. Using .Then() and .Catch() allow the callback functions to only execute once the promise is met or errors out. Once the promise that Fetch() makes is met, .Then() is passed a response depending on the endpoint of the url. This response isn't something we can directly interact with using Javascript so to fix that it needs to be converted to JSON.

function getData() {    fetch(url)    .then(response => response.JSON())    .then(responseArr => {        //function to manipulate JSON data    })}

What is JSON?

JSON is short for JavaScript Object Notation and it is a format of data easily manipulated by JavaScript. It is important to know however that Javascript is not the only programming language that can use JSON data.

A JSON file might look something like this:

[    {        'Name': 'Todd',        'Age': 17,        'Friends': [            'Alex',            'Rebecca',            'Sam'        ]    }    {        'Name': 'Amanda',        'Age': 32,        'Friends': [            'Michael',            'Brett',            'Nita'        ]    }]

JSON data is basically a bunch of javascript-like objects inside of an array. .JSON() that was used in the first .Then() function is a built in method that converts the readable stream passed into it by the promise into JSON.

After the promise is made into JSON data we're then able to pass that JSON array into another .Then() function.

Handling errors

function getData() {    fetch(url)    .then(response => response.JSON())    .then(responseArr => {        //function to manipulate JSON data    })    .catch(error => {        //function to handle error    })}

Some times our Fetch() function will error out, this is when the .Catch() function executes it's code. It is however very uncommon for Fetch() to error out, the only thing that won't return a promise is a network issue.

As a side note while it isn't required to use arrow functions and callback functions I find it a lot cleaner and helps me write more simple DRY code.Instead of writing out something like:

.then(response => response.JSON()).then(response, function(response) {    //function to handle the response})

You can use callbacks and arrow functions to simplify your code and insure each function is single purpose like this:

.then(response => response.JSON()).then(callBack())callBack(arr) {    //function to manipulate data in JSON array}

HTTP Verbs

The examples above have all shown how you can get data from a server, but retreiving data isn't the only way we need to be able to interact with data. What if we need to delete data? What if we need to add data to our database? There are four basic actions we could expect to do with our data- create, request, update and delete or CRUD for short. Each letter in CRUD represents a different HTTP verb. You can think of HTTP verbs as ways to desribe the action our fetch is doing, or as each verb representing a different part of CRUD. Fetch() by default will assume you want to make a GET request to the url that is passed in. The other HTTP verbs are POST, PUT and DELETE. Each verb will represent either creating, reading, updating or deleting data from your database. Since Fetch() defaults to using GET you don't have to specify which kind of request you're making, however with all of the other verbs you will need to tell the function which kind of request you want to make.

POST - CREATE

GET - RECEIVE

PUT - UPDATE

DELETE - DELETE

GET

As I said earlier GET is the default HTTP verb that is used when using Fetch(). GET in my opinion is the easiest of the verbs to understand and is definitely the simplest to write. You pass Fetch() a url and use .Then() to add asynchronous functions to operate over the data returned after the promise is met.

function getData() {    fetch(url)    .then(response => response.JSON())    .then(callBack())//callback funcion to handle data from response    .catch(error => {        //function to handle error    })    }function callBack(arr) {    ///function to manipulate JSON array}

This function is similar to one of the examples from above. The function getData() fetches data from a url, then passes that response into an arrow function that converts the readable stream response into a JSON array that we can iterate over and manipulate using JavaScript.

Headers

We use headers when using Fetch() to define certain parts of the request that might differ for each request. GET doesn't require a header but for every other HTTP verbs we use a header to tell our browser what kind of request we're making. Inside these headers we include things like what kind of request we're making, what parts of the data is being changed and what format new data is if necessary. Every HTTP verb will require different content inside of the header, for example POST requires the method as well as what format our data will be sent in looking something like this:

fetch(url, {    method: 'POST',    headers: {        'content-type': 'application/JSON',        Accept: 'application/JSON'    },    body: JSON.stringify(newData)}

POST

POST is used to create or add data to the database. As you saw in the examples above you make a POST request by defining POST as the method in the header object. You will also need to define what format the data you're sending is coming in. Inside the headers value will be another object defining that format. Then in the body value you define what it is you'll be adding to the database. You'll need to convert the data into a JSON string to make the request.

let newData = {    key1: 'value1',    key2: 'value2'}function addData(){fetch(url, {    method: 'POST',    headers: {        'content-type': 'application/JSON',        Accept: 'application/JSON'    },    body: JSON.stringify(newData)}).then(response => response.JSON()).then(responseArr => /*function to handle data on client side*/ )}

PATCH

PATCH is used to make changes to existing data. PATCH will require you to define it as the method and it will also require you to define headers and a body. There is another HTTP Verb 'PUT' that can also be used to update data. PUT is best if the whole object you're targeting needs to be edited or changed as you'll have to pass a whole new object to replace what you're changing anyways. PATCH only requires you to specify the new value of the key you're changing in the object and that's all that will be updated.

Just like POST you'll need to define what the format for the data that you're sending is coming in, as well as make sure that you're sending the data in that format.

let newData = {    key4: 'value4'}function changeData(){    fetch(url, {        method: 'PATCH',        headers: {            'content-type': 'application/JSON',            Accept: 'application/JSON'        },        body: JSON.stringify(newData)    })}

DELETE

DELETE is used to delete data from the database, other than GET this is probably the most straight forward Fetch() request to make. DELETE will remove all of the data depending on the id of the data that needs to be deleted. You don't need a header on a DELETE request, you just need to specify the method that you want to use and pass in a url with an endpoint that points to the id of the data to be removed. This would look something like this:

function deleteItem() {    fetch(url, {        method: 'DELETE',    })    .then(response => response.JSON())    .then(obj.remove())}

Summary

Fetch() is important to understand as it allows us to interact with data not inside our JavaScript file. CRUD describes the four different uses for Fetch() and the four HTTP verbs that we can use with Fetch() to make requests. It's important to remember what each step of the function actually returns and passes to the next .Then(), use console.log() to make sure you're getting what you expect if you aren't sure.

Here are some more resources you might find useful to learn more about using Fetch(), CRUD, HTTP verbs, and promises in JavaScript:

https://developer.mozilla.org/en-US/docs/Web/API/Response

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

https://www.javascripttutorial.net/javascript-fetch-api/

https://developer.mozilla.org/en-US/docs/Glossary/CRUD

https://www.tjvantoll.com/2015/09/13/fetch-and-errors/

https://learnwithparam.com/blog/how-to-handle-fetch-errors/

https://stackoverflow.com/questions/6203231/which-http-methods-match-up-to-which-crud-methods


Original Link: https://dev.to/kadeesterline/everything-you-need-to-know-about-fetch-3ndf

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To