Typeerror: items.map is not a Function

Asked

Viewed 11,598 times

2

I made a request in a URL via Fetch, however it returns me an error when I ask for the mapping of the json, someone knows how to solve ?

I’ve hidden the URL because it’s private.

import React, { Component } from 'react';


class App extends Component {
 constructor(props){
 super(props);
 this.state = {
 items:[],
 isLoaded: false,
 }
 }

componentDidMount(){
fetch('***')
  .then(res => res.json())
  .then(json => { 
    this.setState({
      isLoaded: true,
      items : json,
    })
  });
 }

render() {

var{isLoaded, items} = this.state;

if(!isLoaded){
  return <div>Loading..</div>
}
else{

return (
    <div className="App">
      <ul>
        {items.map(item => (
          <li key = {item.id}>
            Name : {item.name} | {item.name}
          </li>
        ))};
      </ul>    
    </div>
  );
 }
}
}

export default App;
  • Apparently it does not recognize items as an array

  • On the return of his call ". then(res => res.json()) ", try placing a console.log() and checking what is returning from the api because as Lucas Brogni quoted it may be that the api is not returning an array ....

1 answer

1

The first thing you should do is give a console.log(res.json()) to know what is coming in this request. The .map will only be executed if it is an array, if something is coming in that res json.() use the command typeof to check the type. Certainly what is passing to that Sponse is not an array, or is passing nothing.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.