fetch api in javascript

Fetching APIs in JavaScript can be done using the fetch() method which is a part of the Web APIs. The fetch() method returns a Promise that resolves to the Response object. Here's an example of how to use the fetch() method to get data from an external API:

index.tsx
async function getAPIData(apiEndpoint) {
  try {
    const response = await fetch(apiEndpoint);
    const data = await response.json();
    return data;
  } catch (error) {
    console.log(error);
  }
}
203 chars
10 lines

In the above code, we use the async/await syntax to handle the Promise returned by the fetch() method. The await keyword is used to wait for the Promise to resolve before moving on to the next line of code. The json() method is used to extract the JSON data from the Response object.

Here's an example of how to call the getAPIData() function:

index.tsx
const API_ENDPOINT = 'https://jsonplaceholder.typicode.com/posts';
getAPIData(API_ENDPOINT)
  .then(data => console.log(data))
  .catch(error => console.log(error));
166 chars
5 lines

In the above code, we pass the API endpoint to the getAPIData() function, which returns the data retrieved from the API in JSON format. We then use the .then() method to log the data to the console or the .catch() method to log any errors that occurred.

gistlibby LogSnag