1

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.

4
  • Can you elaborate on "unable to do it"? What output are you expecting, what are you getting, and are there errors? Can you provide a minimal reproducible example? This code doesn't show any actual API calls, just strings being pushed onto an array. Thanks. Commented Nov 22, 2019 at 0:54
  • @ggorlen Okay! So i want to call api using the array which contains the url string. Commented Nov 22, 2019 at 1:04
  • Did you try calling fetch(yourUrlString)? Commented Nov 22, 2019 at 1:05
  • 2
    Take a look at Promise.all for working with an array of asynchronous stuff Commented Nov 22, 2019 at 1:20

2 Answers 2

2

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>
Sign up to request clarification or add additional context in comments.

2 Comments

It say arrayData.push(myJson); myJson is not defined
Sorry it was my mistake. Can you check now.
1

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);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.