async await fetch data api in javascript

index.tsx
async function getData() {
  try {
    const response = await fetch('https://example.com/api/data');
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.log(error);
  }
}

getData();
226 chars
12 lines

In the above code, we have an async function named getData which uses the await keyword to wait for the response of the API request made using the fetch function. We then extract the JSON data from the response using the json method and log it to the console. The try-catch block is used to handle any potential errors that may occur during the API request. Finally, the getData function is invoked which will initiate the API call and log the response data to the console.

gistlibby LogSnag