Reputation: 430
State:
constructor(props) {
super(props);
this.state = {
id: [],name:[]
Fetch:
componentDidMount() {
axios.get('some_api')
.then(res => {
let x = res.data.results.map(obj => obj.id);
let y = res.data.results.map(obj => obj.full_name);
this.setState({id: x});
this.setState({name: y});
})
}
Render:
{this.state(i need to map both id and name here).map((item=>{
return(
<tbody>
<tr>
<td style={{textAlign:'center'}}><Checkbox/></td>
<td style={{textAlign:'center'}}>{item.id}</td>
<td style={{textAlign:'center'}}>{item.full_name}</td>
</tr>
</tbody>)
}))}
I am able to fetch values from one object property, but not all. Data is in this format :
"results": [
{
"id": 25,
"full_name": "William Lane",
"email": "[email protected]",
"username": "staff_24"
},
{
"id": 26,
"full_name": "Christine Thompson",
"email": "[email protected]",
"username": "staff_25"
}
And I have to return it into table form as in the above code.
Upvotes: 0
Views: 5473
Reputation: 673
Look at this example to get all your github repos:
import React, { Component } from 'react'
import axios from 'axios'
import Checkbox from '@material-ui/core/Checkbox'
class MyGitHubRepos extends Component {
state = {
data: []
}
componentDidMount() {
const user = '<YOUR_USER>'
axios.get(`https://api.github.com/users/${user}/repos`)
.then(res => {
const data = res.data
this.setState({ data })
})
}
cell = content =>
<td style={{textAlign: 'center'}}>
{content}
</td>
render() {
return (
<table>
<tbody>
{this.state.data.map(item=> (
<tr key={item.id}>
{this.cell(<Checkbox/>)}
{this.cell(item.id)}
{this.cell(item.name)}
</tr>
))}
</tbody>
</table>
)
}
}
export default MyGitHubRepos
Check out the way you obtain data (the shape of res
in componentDidMount
). Your data should save in an array (no two arrays with ids and names), this is
a little unintelligible. And, if you want, create a function to render a cell to avoid repeat code.
I hope it helps you.
Upvotes: 1
Reputation: 576
You can try this.
class Test extends Component {
constructor(props) {
super(props);
this.state = {
tableData:[]
};
}
componentDidMount() {
axios.get('some_api')
.then(res => {
this.setState({
tableData: res.data.results
})
})
}
render() {
<div>
<table>
<tbody>
{this.state.tableData.map((item,i)=>
<tr id={i}>
<td style={{textAlign:'center'}}><Checkbox/></td>
<td style={{textAlign:'center'}}>{item.id}</td>
<td style={{textAlign:'center'}}>{item.full_name}</td>
</tr>
)}
</tbody>
<table>
</div>
}
}
Upvotes: 1