Deke
Deke

Reputation: 4649

TypeError: this.state.data.map is not a function despite setting data: [ ]

I'm trying to store the data in ItemLists component for which I need to first map over. But getting TypeError: this.state.data.map is not a function

constructor(props) {
  super(props);
  this.state = {
    data: []
  }
}

componentDidMount() {    
  fetch('items.json')
  .then(function(response) {
    if (response.status >= 400) {
      throw new Error("Bad response");
    }
    return response.json();
  })
  .then(data => {
    console.log(data)
    this.setState({data: data});
  });
}


render() {     
  return (
    <div className="App">
      {this.state.data.map(function(object){
        return (
          <ItemLists key={object.id} data={object}/>
        )
      })}
    </div>
  );
 }
}

if I change the code to:

render() {     
  return (
    <div className="App">
      return (
        <ItemLists data={this.state.data}/>
      )
    </div>
   )
 }

error I get is: Objects are not valid as a React child (found: object with keys {artist, title, level, released, rating}). If you meant to render a collection of children, use an array instead pointing towards this.setState({data: data});

json data:

  {
    "data": [
      {
        "name": "cnt",
        "level": "12"
      },
      {
        "name": "stewart",
        "level": "6"
      },
      {
        "name": "nic",
        "level": "7"
      }
    ]
  }

Upvotes: 1

Views: 196

Answers (2)

Tholle
Tholle

Reputation: 112787

After the fetch request is completed you set the data array in your state to the parsed JSON object. Since regular objects don't have a map method like arrays have, you get the error.

You could set the data in state to be the data array in the parsed JSON object instead.

componentDidMount() {    
  fetch('items.json')
  .then(response => {
    if (response.status >= 400) {
      throw new Error("Bad response");
    }
    return response.json();
  })
  .then(response => {
    this.setState({ data: response.data });
  });
}

Upvotes: 2

kyun
kyun

Reputation: 10264

You should use Arrow function when you use the function in React Component

let JSONDATA = 
  {
    data: [
      {
        name: "cnt",
        level: "12"
      },
      {
        name: "stewart",
        level: "6"
      },
      {
        name: "nic",
        level: "7"
      }
    ]
  }

let { data } = JSONDATA;

data.map((obj)=>{
  console.log(obj)
})

Upvotes: 1

Related Questions