fetch in javascript

To make an HTTP request and get data in JavaScript, the Fetch API can be used. It provides a simple interface for fetching resources asynchronously across the network.

Here's an example of how to make a GET request using the Fetch API:

index.tsx
fetch(url)
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error))
123 chars
5 lines

In the above code, the fetch function takes the URL of the resource you want to fetch as its argument. It returns a Promise that resolves to the Response object representing the response to the request.

The then method is chained onto the Promise returned by the fetch function. It takes a callback function that will be called once the request is successfully completed. In this callback function, the json method is used to extract the JSON data from the response object.

If there is an error during the request or parsing the response data, the catch method will be called with the error object.

Alternatively, you can use async/await with fetch to simplify the code and handle errors more elegantly:

index.tsx
async function getData(url) {
  try {
    const response = await fetch(url);
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error(error);
  }
}

getData(url);
207 chars
12 lines

In the above code, the getData function is declared as async. It uses the await keyword to wait for the fetch request to complete and the JSON data to be parsed. If there are any errors, they are caught by the try/catch block.

gistlibby LogSnag