Home > Mobile >  Fetch API in Javascript
Fetch API in Javascript

Time:07-14

I want to render a list from an API but the problem is I am able to console.log the element I want to render but I am not able to render it into the HTML side below is the code. when I use <li>${element}</li> it gives an error.

const url1 = "https://jsonplaceholder.typicode.com/users/1"
const url2 = "https://jsonplaceholder.typicode.com/users/2"
const url3 = "https://jsonplaceholder.typicode.com/users/3"
const fData = document.getElementById('fData')

async function fetchApis() {
  const results = await Promise.all([fetch(url1), fetch(url2), fetch(url3)])
  const responseAll = results.map(result => result.json())
  const finalData = await Promise.all(responseAll)
  console.log(finalData)
  const finalDataToString = finalData.map(function(arraydata) {
    return arraydata.name
  })
  fData.innerHTML = `${finalDataToString.forEach(element => {
    console.log(element)
   })}`
}
fetchApis()
<ul id="fData"></ul>

CodePudding user response:

You can break the code down a little to make your life easier.

  1. Put the URLs in an array to start with.
  2. map over the URLs array and call apiCall on each iteration to return an array of promises.
  3. await Promise.all(promises).
  4. You now have an array of data objects. map over that array and return the HTML you want in a template string.
  5. Finally add that HTML string to the element (which should be a ul or ol if you want to return list items.

// Return a promise of data to come
function apiCall(url) {
  return fetch(url)
    .then(res => res.json())
    .catch(err => console.log(err));
}

async function getData(urls) {

  // `map` over the urls array and for each iteration
  // call `apiCall`. An array of promises is returned
  const promises = urls.map(apiCall);

  // Get the data from the promises
  const data = await Promise.all(promises);

  // Finally `map` over the array of objects and return
  // a template string with the object name value
  return data.map(obj => `<li>${obj.name}</li>`).join('');
}

// `await` the call to `getData`, and then
// add the HTML to the list element
async function main(el, urls) {
  const html = await getData(urls);
  el.insertAdjacentHTML('beforeend', html);
}

const urls = [
  'https://jsonplaceholder.typicode.com/users/1',
  'https://jsonplaceholder.typicode.com/users/2',
  'https://jsonplaceholder.typicode.com/users/3'
];

const el = document.querySelector('#fData');

main(el, urls);
<ul id="fData"></ul>

CodePudding user response:

Your code only does a console.log, you do not wrap in LI

Here I use an Array.map

And I get the name using destruct in an arrow function

const url1 = "https://jsonplaceholder.typicode.com/users/1"
const url2 = "https://jsonplaceholder.typicode.com/users/2"
const url3 = "https://jsonplaceholder.typicode.com/users/3"
const fData = document.getElementById('fData')

async function fetchApis() {
  const results = await Promise.all([fetch(url1), fetch(url2), fetch(url3)])
  const responseAll = results.map(result => result.json())
  const finalData = await Promise.all(responseAll)
  // finalData contains an array of all data fetched
  // create an array of name wrapped in LI and join with spaces
  fData.innerHTML = finalData.map(({name}) => `<li>${name}</li>`).join("")
}
fetchApis()
<ul id="fData"></ul>

  • Related