Nirmal Patel
Nirmal Patel

Reputation: 71

How to fetch api from the function which pushes each api in array?

I am trying to get API data so i can render it on Webpage using ReactJS. I tried many different ways to fetch api where its stored in array. But i am unable to do it.

Note:https://www.hatchways.io/api/assessment/workers/<worker_id> Here i'm looping so the worker id gets add the of url.

const fetchAPI = e => {
    let array = [];
    const api2 = `https://www.hatchways.io/api/assessment/workers/`;

    for (var i = 0; i <= 4; i++) {
      array.push(api2 + i);
    }
    return array;
  };
  console.log(fetchAPI());

Thanks in advance.

Upvotes: 1

Views: 180

Answers (2)

Asad Zaman
Asad Zaman

Reputation: 485

You need to hit the url first. Async/Await would be a good choice.

<script>
  async function check()
  {
    var arrayData =[];
    var url = "https://www.hatchways.io/api/assessment/workers/";
    for(var i=1;i<=4;i++)
    {          
      const response = await fetch(url+""+i);
      const myJson = await response.json();
      arrayData.push(myJson);
    }
    console.log(arrayData)

  }
  check();
</script>

Upvotes: 2

ricardoorellana
ricardoorellana

Reputation: 2340

Use Promise.all for example:

const baseURL = 'https://jsonplaceholder.typicode.com';

const fetchUsers = fetch(`${baseURL}/users`);
const fetchPosts = fetch(`${baseURL}/posts`);

Promise.all([fetchUsers, fetchPosts]).then((responses) => {
  const responsesToJson = responses.map(response => response.json());
  
  return Promise.all(responsesToJson);
}).then((jsonResponse) => {
  const [userResponse, postResponse] = jsonResponse;
  
  console.log(userResponse);
  console.log(postResponse);
});

Upvotes: 1

Related Questions