fetch data from api in javascript

Fetching data from an API in JavaScript can be achieved using the fetch() function, which is built-in to modern browsers. The fetch() function returns a Promise, which we can use to handle the response received from the API.

Here's an example of how to use fetch() to fetch data from an API:

index.tsx
// define the URL of the API
const apiUrl = 'https://jsonplaceholder.typicode.com/todos/1';

// make a request to the API using fetch()
fetch(apiUrl)
  .then(response => {
    if (response.ok) {
      // if the response is okay, parse the data as JSON
      return response.json();
    } else {
      throw new Error('Network response was not okay.');
    }
  })
  .then(data => {
    // do something with the data
    console.log(data);
  })
  .catch(error => {
    // handle any errors
    console.error('There was an error fetching the data:', error);
  });
561 chars
22 lines

In the code above, we first define the URL of the API we want to fetch data from. We then make a request to the API using fetch(), which returns a Promise. We chain a series of then() methods to the Promise to handle the response received from the API.

The first then() method checks if the response received from the API is okay (i.e. the API returned a 200 OK HTTP status code). If the response is okay, we parse the response data as JSON and return it. If the response is not okay, we throw an error.

The second then() method receives the parsed JSON data and allows us to do something with it (e.g. display it on the page, manipulate it in some way, etc.).

Finally, we chain a catch() method to the Promise to handle any errors that may have occurred during the fetch request.

Alternatively, we can use async/await syntax to simplify the code:

index.tsx
async function fetchData() {
  try {
    const response = await fetch(apiUrl);
    if (!response.ok) {
      throw new Error('Network response was not okay.');
    }
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error('There was an error fetching the data:', error);
  }
}

fetchData();
336 chars
15 lines

In the code above, we define an async function called fetchData() which makes a request to the API using fetch() and handles the response using await and try/catch syntax. We then call the fetchData() function to initiate the fetch request.

gistlibby LogSnag