fetch then api in javascript

To fetch data from an API in JavaScript, you can use the fetch() function or the XMLHttpRequest (XHR) object.

Here's an example of using fetch():

index.tsx
fetch('https://example.com/api/data')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));
151 chars
5 lines

This code sends a GET request to https://example.com/api/data, parses the received JSON data, and logs it to the console. It also catches any error that might occur during the operation.

Here's an example of using XHR:

index.tsx
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
  if (this.readyState === 4 && this.status === 200) {
    const data = JSON.parse(this.responseText);
    console.log(data);
  }
};
xhr.open("GET", "https://example.com/api/data");
xhr.send();
265 chars
10 lines

This code creates an XHR object, sets a callback function to be called when the response is ready, and sends a GET request to https://example.com/api/data. When the response is received, the callback function parses the JSON data and logs it to the console.

Both fetch() and XHR are asynchronous functions, meaning that they don't block the main thread while waiting for the response. Asynchronous programming is essential in web development, especially when dealing with APIs, as it allows the UI to remain responsive while the data is being fetched.

gistlibby LogSnag