Skip to content
Advertisement

ReactJS “Unhandled Rejection (TypeError): this.state.features.map is not a function”

I’m learning React and now I’m trying to do a get request and list with map but when I run this code they come up with this error “Unhandled Rejection (TypeError): this.state.features.map is not a function”. I have already searched this but I do not understand what is going on.

   import React, { Component } from 'react';
import './App.css';

class App extends Component {

  constructor() {
    super();
    this.state = {
      features: [{
        id: 1,
        name: 'Test',
        count: 1
      }]
    }
  }

  componentWillMount() {
    fetch("http://demo6085176.mockable.io/features")
      .then(response => response.json())
      .then(json => {
        console.log(json);
        this.setState({
          features: json,
        });
      });
    console.log(this.state.features)
      
  }

  render() {
    return (
      <div className="App">
        <ul>
          {
            this.state.features.map(function(feature){
              return (
                <li key={feature.id}><button type="button">Upvote</button> ({feature.count}) <span>{feature.name}</span></li>
              )
            })
          }
        </ul>
      </div>
    );
  }
}

export default App;

Advertisement

Answer

In your componentWillMount, just do this:

componentWillMount() {
   fetch("http://demo6085176.mockable.io/features")
    .then(response => response.json())
    .then(json => {
      console.log(json);
      this.setState({ features: json.features });
   });
}

The response you get from the API is an object which has a key of features which is an array of objects of the data you want.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement