Fetching data map error!

Hi!

I am trying to fetch data from github api as written in a tutorial, but I am running into an error:

TypeError: Cannot read property ‘map’ of undefined

I don’t know why but for a few times it worked, but then it stopped and when built it does not render the page at all.

Here is the code:

import { Component, State } from '@stencil/core';

@Component({
  tag: 'app-coin-list',
  styleUrl: 'app-coin-list.css'
})
export class AppCoinList {

@State() users : Array<any>;

componentWillLoad() {
  let url = 'https://api.github.com/users';
  fetch(url).then(response => {
    response.json().then(json => {
      this.users = json;
      console.log(this.users)
    });
  });
}

  render() {
    return [
      <ion-header>
        <ion-toolbar color="primary">
          <ion-buttons slot="start">
            <ion-back-button defaultHref="/" />
          </ion-buttons>
          <ion-title>CoinList</ion-title>
        </ion-toolbar>
      </ion-header>,

      <ion-content padding color="primary">


        <ion-list lines="full">
          {this.users.map(user =>
            <ion-item color="secondary">
              <ion-label>{user.login}</ion-label>
            </ion-item>
          )}
        </ion-list>

      </ion-content>
    ];
  }
}

Also… this does not work when using for example coinmarketcap api which returns nested array. How would I go about using that?

Thank you
leon

Have not used Stencil but within Ionic 3.x, this is how I process a GET call.

this.http.get(URL,options).map(res => res.json()).subscribe(data => {

});

1 Like

Ok so I got it working by using:

<ion-list lines="full">
          {this.users && this.users.map(user =>
            <ion-item color="secondary">
              <ion-label>{user.login}</ion-label>
            </ion-item>
          )}
        </ion-list>

So putting a check (this.users &&) in front of this.users.map.

I would like to understand why that worked :smile:, but at least it works.

Thanks to React and its stackoverflow community!
link

And thank you for your answer danieldugger!

Leon