Fetch using for Get method in JavaScript

naveen-golla , Credit to  volkotech-solutions Nov 02
fetch

In this blog, we are going to learn about how to use fetch in JavaScript. Fetch provides a JavaScript interface for accessing the data and manipulating the HTML pipeline.

What is fetch()?

Fetch is a mechanism that lets you make simple AJAX calls from JavaScript. AJAX stands for Asynchronous JavaScript and XML.

Asynchronous is like a promise to API calls. If you request any fetch API from external it allows JavaScript to run another function in your JavaScriptif the fetch API call has not been resolved.

  • It is important to note that fetch is not a part of JavaScript.

How to use fetch()?

We know that fetch is not a part of JavaScript we get data from external API. First, we take any random API in this lecture I used blog posts API link

fetch('https://ubahthebuilder.tech/posts/');

Below is the API link for blog posts data for using this data we can get random blog posts

fetch('https://ubahthebuilder.tech/posts/1'); 

In this API link, we use to get the first blog object

{
      userId : 1,
	  id : 1,
      title : ‘A post by Naveen’,
      body : ‘How to use fetch in javascript’
};

Convert Fetch() to JSON() object format

We get data from the network and convert it into object format.

fetch('https://ubahthebuilder.tech/posts/1')

.then(data => {
      return data.json();
})
    .then(post => {
    console.log(post.title);
});

The above function is to format the API to JSON() object. The function inside first  .then() blocks the network from the server response. The function inside the second is to get data of the first blog post.

Get request

The data returned from the API is not unusable; you need to convert that into a usable format. In JavaScript, there is a method called JSON() use this method to convert unusable data to usable data.

fetch('https://ubahthebuilder.tech/posts/1')

  .then(data => {
     return data.json();
  })
fetch.p

Using Async and Await functions

Async: Async function will always return a value it makes sure of a promise and it is not returned then JavaScript automatically wraps it in a promise which is resolved with its value.

Await: Await function is used to wait for the promise means it is waiting for the function to get data after that the function will execute. It could be used in an async block only if it waits until the promise returns the result. It only makes the async block wait.

stynt

Conclusion

Computer systems like software communicate with each other and share information through a layer called an API. We acquire data from APIs by using the fetch function and passing the URL as an argument.

That's all I have for now; I hope you understand. Thank you for taking the time to read!  Please share and leave a comment below

Comments

Authors

Read Next