Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React map got item is not defined

I got repo is not defined. But I console.log(json.items) I can see the arrays.

const githubRepo = React.createClass({
  getInitialState(){
    return {
      repo: []
    }
  },
  componentWillMount(){
    fetch('https://api.github.com/users/abc/repos')
     .then(response => {
      return response.json()
    }).then(json => {
      this.setState({repo: json.items})
    })
  },
  render(){
    return(
      <div>
        <ul>
          {
            this.state.repo.map(repo => 
              <li>{repo .name}</li>
            )
          }
        </ul>
      </div>
    )
  }
})

Something is wrong with my map function? componentWillMount means execute before render, hmm take should make sense. Can't find my mistake.

https://jsfiddle.net/pvg1hg0s/

like image 627
Cassie Avatar asked Nov 16 '25 20:11

Cassie


1 Answers

You need to change json.items to just json.

this.setState({repo: json})

Here is an updated jsfiddle.

Your componentWillMount method should look like this

fetch('https://api.github.com/users/abc/repos')
.then(response => {
  return response.json()
}).then(json => {
  this.setState({repo: json})
})

The reason is that the response which you are referencing as json does not have any keys with item hence this was returning undefined. It is actually returning an array which you can then loop over with map. Firstly you will need to set the value of json to the response of the API call using setState.

like image 177
Paul Fitzgerald Avatar answered Nov 19 '25 09:11

Paul Fitzgerald



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!