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/
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With