DEV Community

CodeMonk
CodeMonk

Posted on • Updated on

ChatGPT helped me to convert my code from Xml API to Fetch API

## I USED AN OPEN API-REST COUNTRIES-
MY PROMPT - could you convert my code from xml api to fetch api

ChatGPT - Certainly! Please provide me with the code snippet you would like to convert from XML API to Fetch API, and I'll do my best to assist you with the conversion.

My code-

'use strict';

const btn = document.querySelector('.btn-country');
const countriesContainer = document.querySelector('.countries');

///////////////////////////////////////
const country = function (country) {
  const request = new XMLHttpRequest();
  request.open('GET', `https://restcountries.com/v3.1/name/${country}`);
  request.send();
  request.addEventListener('load', function () {
    const [data] = JSON.parse(this.responseText);
    console.log(data);
    let curr = data.currencies[Object.keys(data.currencies)[0]];
    const html = `
  <article class="country">
  <img class="country__img" src="${data.flags.png}" />
  <div class="country__data">
          <h3 class="country__name">${data.name.official}</h3>
          <h4 class="country__region">${data.subregion}</h4>
          <p class="country__row"><span>👫</span>${(
            +data.population / 1000000
          ).toFixed(1)} people</p>
          <p class="country__row"><span>🗣️</span>${data.languages.eng}</p>
          <p class="country__row"><span>💰</span>${curr.name}</p>
        </div>
        </article>
        `;
    countriesContainer.insertAdjacentHTML('beforeend', html);
  });
};

country('usa');
country('canada');
Enter fullscreen mode Exit fullscreen mode

ChatGPT -

'use strict';

const btn = document.querySelector('.btn-country');
const countriesContainer = document.querySelector('.countries');

///////////////////////////////////////
const country = function (country) {
  fetch(`https://restcountries.com/v3.1/name/${country}`)
    .then(response => response.json())
    .then(data => {
      const [countryData] = data;
      console.log(countryData);
      let curr = countryData.currencies[Object.keys(countryData.currencies)[0]];
      const html = `
        <article class="country">
          <img class="country__img" src="${countryData.flags.png}" />
          <div class="country__data">
            <h3 class="country__name">${countryData.name.official}</h3>
            <h4 class="country__region">${countryData.subregion}</h4>
            <p class="country__row"><span>👫</span>${(
              +countryData.population / 1000000
            ).toFixed(1)} people</p>
            <p class="country__row"><span>🗣️</span>${countryData.languages.eng}</p>
            <p class="country__row"><span>💰</span>${curr.name}</p>
          </div>
        </article>
      `;
      countriesContainer.insertAdjacentHTML('beforeend', html);
    });
};

country('usa');
country('canada');
Enter fullscreen mode Exit fullscreen mode

Top comments (0)