How to Use the JavaScript Fetch API to Get Data

Spread the love

There was a time when JavaScript Fetch API I requests were made using XMLHttpRequest. It lacked Promises and resulted in unclean JavaScript code. You could use the cleaner syntax of jQuery instead. ajax().

JavaScript now has its built-in method for making api requests. This is the Fetch api, a new standard for making server requests using Promises that includes extra features.

Fetch api to create GET and POST requests.

This task aims to demonstrate how to use the Fetch api to retrieve data from an api. For example, I will use a fictitious api containing employee information. I’ll demonstrate how to get data using the Fetch () api method.

The Fetch () method in JavaScript is modern and versatile, and modern browsers widely support it. It can send network requests to the server and load new information without reloading the browser.

The Fetch () method takes only one mandatory argument, which is the URL of the resource to be retrieved.

([response = fetch(api url, [other parameters])

Awaiting JavaScript Async: In this example, we will use the Async Await method in conjunction with the To make promises more concisely, use the Fetch () method. All modern browsers support async functions.

Prerequisites

You will need the following items to complete this tutorial:

  • A Node js local development environment. Follow How to Install Node.js and Create a Local Development Environment.
  • You have a fundamental understanding of JavaScript coding, which you can learn more about by visiting the How to In the JavaScript series and writing code.
  • An understanding of JavaScript Promises. Read the Promises section of this article on JavaScript’s event loop, callbacks, Promises, and async/await.

Step 1: Understanding Fetch api syntax

One method for using the Fetch api is to pass the URL of the api as a parameter to

fetch(url)

A Promise is return by the fetch() method. Include the Promise method then() after the fetch() method:

fetch(url) .then(function(){ // handle the response })

If the Promise returned is resolved, the then() method’s function is executed. This function contains the code for dealing with the api data.

Include the catch() method after the then() method:

fetch(url)
  .then(function() {
    // handle the response
  })
.catch(function() {    // handle the error
  });

The api you call with Fetch () may be unavailable, or other errors may occur. So, if this occurs, the reject promise is return. To handle rejection, the catch method is use. If an error occurs while calling the api of your choice, the code within the catch() will be execute.

You can now use Fetch () on a real api after you’ve mastered the syntax for using the Fetch api.

Step 2 — Obtaining Data from an api using Fetch


The JSONPlaceholder api will be use in the following code samples. So, you will get ten users from the api and use JavaScript to show them on the page. This tutorial will pull information from the JSONPlaceholder api and show it in the form of list items within the framework of the author’s list.

Begin by creating an HTML file and inserting a heading and an unordered list with the authors’ ids:

Authors.html

<h1>Authors</h1>

<u1 id=”authors”></u1>

And show them on the document using JavaScript. This tutorial pulls data from the JSONPlaceholder api and displays it.

Authors.html

<h1>Authors</h1> <u1 id=”authors”></u1>

<script> conset u1 = document.getElement Byld ( ‘authors’ ); </script>

Remember that the author is the id for the previously create ul.

Create a list that is a Document Fragment next:

Authors.html

<script>
  // ...
   
  const list = document.createDocumentFragment();
</script>

All attached list items will be included in the list. Then the active document tree structure does not include a DocumentFragment. When the Document Object Model is changed, this prevents performance-impacting redraws.

Create a constant variable called url that will hold the JavaScript Fetch API URL for returning ten random users:

Authors.html

<script>
  // ...

  const url = 'https://jsonplaceholder.typicode.com/users';
</script>

Now, using Fetch api, use Fetch () with the reasoning url to call the JSONPlaceholder api:

Authors.html

<script> // … fetch(url) </script>

You’re using the JavaScript Fetch API. You could use the cleaner syntax to get the URL for the JSONPlaceholder API. Then there is a response. However, the response is an object with a series of methods that can be used depending on what you want to do with the information rather than JSON. Use the JSON () method to convert the returned object to JSON.

Add the then() method, which will contain a function with a response parameter:

Authors.html

<script>
  // ...

  fetch(url)
    .then((response) => {})
</script>

The cost of the component is the object return from fetch (url). To convert the answer into JSON data, use the JSON() process:

Authors.html

<script>
  // ...

  fetch(url)
    .then((response) => {
      return response.json();
    })
</script>

The JSON data must still be process. Add another then() statement with a function with a data argument:

Authors.html

<script>
  // ...

  fetch(url)
    .then((response) => {
      return response.json();
    })
    .then((data) => {})
</script>

Create a variable called authors within this function and set it to data:

Authors.html

<script>
  // ...

  fetch(url)
    .then((response) => {
      return response.json();
    })
    .then((data) => {
      let authors = data;
    })
</script>

Then Create a list item that displays the author’s name for each author in authors. However this pattern is well-suited to the map() method:

Authors.html

<script>
  // ...

  fetch(url)
    .then((response) => {
      return response.json();
    })
    .then((data) => {
      let authors = data;
  
      authors.map(function(author) {
  
      });
    })
</script>

Within your map function, because create a thing called li that will be set equal to createElement with li (the HTML element) as the argument. Then create an h2 for the name and a span for the email:

Authors.html

<script>
  // ...

  fetch(url)
    .then((response) => {
      return response.json();
    })
    .then((data) => {
      let authors = data;

      authors.map(function(author) {
        let li = document.createElement('li');
        let name = document.createElement('h2');
        let email = document.createElement('span');
      });
    })
</script>

The author’s name will appear in the h2 element. The author’s email address will be display in the span element. Then this is possible thanks to the inner HTML property and string interpolation:

Authors.html

<script>
  // ...

  fetch(url)
    .then((response) => {
      return response.json();
    })
    .then((data) => {
      let authors = data;

      authors.map(function(author) {
        let li = document.createElement('li');
        let name = document.createElement('h2');
        let email = document.createElement('span');

        name.innerHTML = ${author.name}`;        email.innerHTML = ${author. Email}`;      });
    })
</script>

Next, use appendChild to relate these DOM elements:

Authors.html

<script>
  // ...

  fetch(url)
    .then((response) => {
      return response.json();
    })
    .then((data) => {
      let authors = data;

      authors.map(function(author) {
        let li = document.createElement('li');
        let name = document.createElement('h2');
        let email = document.createElement('span');

        name.innerHTML = `${author.name}`;
        email.innerHTML = `${author.email}`;
       
        li.appendChild(name);
        li.appendChild(email);
        list.appendChild(li);

      });
    })

  ul.appendChild(list);
</script>

It should be noted that each list item is append to the DocumentFragment list. Once the map is finish, the list is appended to the ul unordered list element.

Because after you’ve finished both the () functions, you can add the catch() function. This function will print the following error message to the console:

Authors.html

<script>
  // ...

  fetch(url)
    .then((response) => {
      // ...
    })
    .then((data) => {
      // ...
    })
    .catch(function(error) {
      console.log(error);
     });
  
  // ...
</script>

This is the complete code for the request you create:

Authors.html

<h1>Authors</h1>
<ul id="authors"></ul>

<script>
  const ul = document.getElementById('authors');
  const list = document.createDocumentFragment();
  const url = 'https://jsonplaceholder.typicode.com/users';

  fetch(url)
    .then((response) => {
      return response.json();
    })
    .then((data) => {
      let authors = data;

      authors.map(function(author) {
        let li = document.createElement('li');
        let name = document.createElement('h2');
        let email = document.createElement('span');

        name.innerHTML = `${author.name}`;
        email.innerHTML = `${author.email}`;

        li.appendChild(name);
        li.appendChild(email);
        list.appendChild(li);
      });
    }).
    .catch(function(error) {
      console.log(error);
    });

  ul.appendChild(list);
</script>

Then you just completed a GET request with the JSONPlaceholder api and the Fetch api.

Conclusion

While not all browsers support the Fetch api, it is a great alternative to XMLHttpRequest. So, if you like to know how to utilize React to call Web apis, you should read this article.

1,409 thoughts on “How to Use the JavaScript Fetch API to Get Data”

  1. Однако и не самый топовый выигрыш варьируется в достаточно высоких размерах, от 2 000 000 до 100 000 рублей. Последняя проиграла буквально всё, а у негра осталась только машина, которую он и поставил на 00, когда блонда поставила свою вагину на 0. Бред какой то. Source: https://shazamm.info/2023/08/02/california-casinos-record-and-gambling-locations-in-ca/

    Reply
  2. Быстровозводимые здания – это современные конструкции, которые различаются громадной скоростью возведения и мобильностью. Они представляют собой сооружения, образующиеся из эскизно созданных компонентов либо компонентов, которые могут быть быстро смонтированы в районе развития.
    [url=https://bystrovozvodimye-zdanija.ru/]Быстровозводимые здания под ключ[/url] отличаются гибкостью также адаптируемостью, что позволяет просто изменять а также адаптировать их в соответствии с интересами клиента. Это экономически продуктивное и экологически стойкое решение, которое в крайние годы приобрело обширное распространение.

    Reply
  3. На сайте https://avantage-sib.ru/ вы сможете заказать звонок для того, чтобы воспользоваться нужной и полезной услугой – размещение рекламы на транспорте. При этом все материалы качественные, надежные и высокотехнологичные. Среди популярных услуг выделяют: автомобильные тенты, изготовление баннеров, широкоформатная печать. Для того чтобы быстрее определиться с выбором, необходимо ознакомиться с отзывами тех, кто уже воспользовался услугами. Копания успешно реализовала несколько тысяч проектов.

    Reply
  4. Поиск арендных предложений в Никосии
    никосия аренда квартиры [url=https://www.kvartira-nikosiya.ru/]https://www.kvartira-nikosiya.ru/[/url].

    Reply
  5. Наш интернет-магазин https://o-savva.ru/product/tehnicheskie-sredstva-reabilitatsii реализует медицинские электрические переносные, компактные и легкие подъемники для инвалидов по приемлемым ценам от 89000 рублей, так же в продаже есть ручные подъемники. Вы сразу поймете насколько проще станет жизнь рядом с лежачим больным человеком, а также будет проще уход за ним.

    Reply
  6. На сайте http://masl-credit.ru/ вы сможете ознакомиться с самыми надежными, популярными, проверенными МФО, которые выдают средства на честных условиях, без отказа. Они работают прозрачно, а потому в честности не приходится сомневаться. В перечисленных учреждениях регулярно занимают средства, а потом отдают с небольшим процентом. На сайте вы сможете воспользоваться такими финансовыми продуктами, как: кредиты, микрозаймы, дебетовые карты. Также есть раздел с лучшими предложениями займов. Изучите их сейчас.

    Reply
  7. [url=https://motoparamoga.vn.ua/uk/v-shiny/primenenie-is-kvadrotsikl-utv-baggi/]motoparamoga.vn.ua/uk/v-shiny/primenenie-is-kvadrotsikl-utv-baggi/[/url]

    Инет-магазин числом перепродаже мотоциклов, квадроциклов, скутеров и другой мототехники «Motoparamoga». Симпатичные стоимости да оперативная экспресс-доставка!
    motoparamoga.vn.ua/uk/v-bagazhniki-kofra/

    Reply
  8. На сайте https://rezumepro.com/ воспользуйтесь такой важной и нужной услугой, как составление профессионального резюме. Сервис располагает первоклассными специалистами, у которых огромный опыт. В обязательном порядке практикуется индивидуальный подход. По этой причине резюме составляется с учетом особенностей отрасли. Вы сможете работать напрямую со специалистом, который в обязательном порядке возьмет на вооружение ваши пожелания. Высококлассные специалисты сэкономят ваше время на том, чтобы создать работающее резюме.

    Reply
  9. Недавно мне понадобилось 19 000 рублей на оплату курсов. В Twitter я нашел ссылку на yelbox.ru. Там представлены советы о том, как взять [url=https://yelbox.ru/]онлайн займ на карту[/url] , и список надежных МФО. И даже организации, предоставляющие займы без процентов!

    Reply
  10. Недавно мне понадобилось 4 000 рублей на неотложные нужды. По совету друга, я посетил yelbox.ru. Там я нашел много полезных статей о том, как правильно взять [url=https://yelbox.ru/]займы на карту онлайн[/url] и список проверенных МФО. И узнал, что некоторые из них предоставляют займы без процентов!

    Reply
  11. Среди многочисленных постов в Instagram мой взгляд привлек рекламный баннер сайта wikzaim. Займы под 0% – это то, что мне нужно было. Я посетил сайт, выбрал МФО из представленного списка и легко получил 9000 рублей без процентов.

    Reply
  12. Бывают ситуации, когда деньги нужны прямо сейчас, даже если это ночь. В таких случаях я всегда выбираю wikzaim. Портал никогда не подводил – микрозаймы от двух МФО оформляются за минуты, и деньги моментально поступают на счет.

    Reply
  13. Представьте, как вы просыпаетесь от легкого морского бриза, открываете глаза и видите бескрайние просторы Черного моря. Это не мечта – это реальность отдыха в отелях Туапсе в 2023 году!

    Наши отели – это место, где каждый день наполнен магией и вдохновением. Мы заботимся о вашем комфорте, предлагая лучшие услуги и удобства. Забронируйте свой идеальный отдых уже сегодня и почувствуйте настоящее волшебство Туапсе!

    Ключевое слово: волшебство. В каждом тексте создается атмосфера уюта, комфорта и волшебства, которые ожидают гостей в отелях Туапсе в 2023 году. Ждем вас открыть этот удивительный мир с нами!

    Reply
  14. Кто сказал, что настоящий рай на земле не существует? Откройте для себя отели Туапсе в 2023 году! У нас каждый гость – особенный, и мы знаем, как сделать ваш отдых идеальным.

    Роскошные номера, завораживающие виды на Черное море, великолепная кухня и сервис мирового класса – все это и многое другое ждет вас. Сделайте свой отпуск незабываемым с нашими отелями в Туапсе!

    Reply
  15. Provider RTG Slot menjadi pilihan alternatif terbaik bagi para penggila permainan judi slot online 303. RTG slot ini sudah dikenal lama sebagai penyedia permainan judi slot 88 gacor 777 dengan hadiah yang amat besar. Hadiah hingga ratusan juta Rupiah bisa didapatkan dari provider RTG Slot ini. Dengan rekam jejak dan pengalamannya, RTG slot akan selalu direkomendasikan sebagai pilihan terbaik untuk para penjudi slot 88 gacor 77. Keuntungan bisa mudah diperoleh dengan memilih RTG slot sebagai pilihan provider utamanya. Slot adalah salah satu permainan yang digemari dalam sebuah Casino, dengan seiring perkembangannya zaman sekarang slot sudah dapat diakses dalam bentuk game Slot Online. GADUNSLOT sebagai salah satu situs slot terlengkap berani menghadirkan 33 Provdier judi slot gacor terbaik dari yang gampang menang hingga jackpot terbesar. Berikut ini adalah Daftar Provider Slot Online Terbaru dan Terbaik di GADUNSLOT:
    https://israeldvoe374780.blog-gold.com/27220344/android-1-com-slots-pharaoh-s-way
    On some parts of the casino floor, machines were grouped in batches of the same machine from the same manufacturer, although different games within the cluster. I’m not sure the reason for this (other than perhaps easier maintenance if you’re doing something to the same machine type across the board), but it did make it sometimes easier to take an educated guess on where to find a certain game, if you knew what machine the game was released. Yes, poker is available at this casino. The casino has a dedicated poker room with plenty of tables and games to choose from. Whether you’re a seasoned pro or a first-time player, you’ll find plenty of action at the Seminole Hard Rock Casino. Hard Rock Casino are a secure choice for online gaming as they’re known worldwide with casinos across the nation. The online casino and sportsbook in New Jersey operates with a license from the NJ Division of Gaming Enforcement. Customers are always safe and secure, with fair games provided by the best developers.

    Reply
  16. Я наконец решился окунуться в мир азарта и нашел прекрасный сайт caso-slots.com. Здесь представлены все популярные казино, а также список тех, где можно получить бонус на первый депозит. Жду не дождусь начала игры!

    Reply
  17. Я ввел в Яндекс запрос “казино на деньги” и первым в списке был сайт caso-slots.com. Здесь я нашел множество казино с игровыми автоматами, а также бонусы на депозит и статьи с полезными советами по игре, что сделало мой выбор в пользу этого сайта еще увереннее.

    Reply
  18. Захотелось новых ощущений и я решил попробовать поиграть в онлайн казино. Сайт caso-slots.com стал моим проводником в этот мир. Теперь у меня есть список популярных казино и тех, где можно получить бонус на первый депозит.

    Reply
  19. Открыв для себя сайт caso-slots.com, я понял, что мир онлайн-казино полон возможностей. Здесь есть все популярные казино, а также список тех, где можно получить бонус на первый депозит. Пора испытать удачу!

    Reply
  20. Привет всем! Я всегда мечтал испытать азарт онлайн-казино, и наконец решился. После небольшого поиска я нашел сайт caso-slots.com, где представлены все популярные казино и даже список тех, где можно получить бонус на первый депозит. Это точно то, что я искал!

    Reply
  21. Захотелось азарта, и я решил найти казино на деньги через Яндекс. На первом месте был сайт caso-slots.com, где представлены различные казино с игровыми автоматами, бонусы на депозит и статьи с советами по игре. Все, что нужно для успешной игры!

    Reply
  22. На сайте https://alkomarketdubai.ru/ закажите качественный, сертифицированный алкоголь, который удивит своим утонченным вкусом, приятным оформлением. Он сделает вашу вечеринку более насыщенной, яркой и незабываемой. Если к вам нагрянули гости или хотите отметить начало отпуска, то скорей заходите на этот сайт, где вы сможете приобрести все, что нужно и в требующемся количестве. Если нужно подкупить алкоголь, то и в этом случае вам поможет этот магазин, в котором ассортимент постоянно обновляется.

    Reply