Tomasz Czechowski
Tomasz Czechowski

Reputation: 285

Cannot read property 'map' of undefined while fetching VANILLA JS

When I launch splitArray(people, 5) and displayContent(0) functions one after another in console, they work perfectly fine, but when I add them with .then() into my fetch method, I get an Uncaught TypeError: Cannot read property 'map' of undefined error.

I'm trying to make my first app that displays JSON file as a table with pagination, sorting methods etc. I've searched for answers here but every thread I've found seems to be about REACT. I'm trying to do this with pure vanilla js.

const endpoint = 'https://api.myjson.com/bins/agowj';
let people = [];
let peeps = [];
fetch(endpoint)
  .then(blob => blob.json())
  .then(data => people.push(...data))
  .then(splitArray(people, 5))
  .then(displayContent(0));

function displayContent(page) {
  let suggestions = document.querySelector('.suggestions');
  let html = peeps[page].map(person => {
    return `
    <tr>
    <td>${person.id}</td>
    <td>${person.firstName}</td>
    <td>${person.lastName}</td>
    <td>${person.dateOfBirth}</td>
    <td>${person.function}</td>
    <td>${person.experience}</td>
    </tr>
    `}).join("");
    suggestions.innerHTML = html;
  };

  function splitArray(arr, size) {
  peeps = [];
  for (i=0; i < arr.length; i += size){
    peeps.push(arr.slice(i, i + size));
  }
  return peeps;
}

How can I make this work?

Upvotes: 1

Views: 112

Answers (1)

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174457

You are passing the result of these methods to then. You need to pass a function instead:

.then(() => splitArray(people, 5))
.then(() => displayContent(0));

Upvotes: 4

Related Questions