Reputation: 1356
I have this React setup, I defined a hook called ApiTable
and have a renderTable
method. What I'm trying to do is get the data from the api endpoint, https://jsonplaceholder.typicode.com/users
and return it into a table with the appropriate category.
Right now it's scrunching up all the columns onto the left side as seen here. Currently, the data isn't showing up and is compacted to the left side. I'm pretty sure I have the table data setup wrong.
Also, I'm not sure if the axios request is supposed to inside the useEffect or not.
https://imgur.com/a/Up4a56v
const ApiTable = () => {
const url = 'https://jsonplaceholder.typicode.com/users';
const [data, setData] = useState([]);
useEffect(() => {
setData([data]);
axios.get(url)
.then(json => console.log(json))
}, []);
const renderTable = () => {
return data.map((user) => {
const { name, email, address, company } = user;
return (
<div>
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Address</th>
<th>Company</th>
</tr>
</thead>
<tbody>
<tr>
<td>name</td>
<td>email</td>
<td>address</td>
<td>company</td>
</tr>
</tbody>
</div>
)
})
}
return (
<div>
<h1 id='title'>API Table</h1>
<Table id='users'>
{renderTable()}
</Table>
</div>
)
};
Upvotes: 1
Views: 9414
Reputation: 20765
You are fetching data correctly, but setting data to state wrongly.
Also when you iterating your data
array, you are printing table head
each time which is wrong and from your data
array address
and company
are object so you cant direct print the object.
You need to do this,
const App = () => {
const url = 'https://jsonplaceholder.typicode.com/users'
const [data, setData] = useState([])
useEffect(() => {
axios.get(url).then(json => setData(json.data))
}, [])
const renderTable = () => {
return data.map(user => {
return (
<tr>
<td>{user.name}</td>
<td>{user.email}</td>
<td>{user.address.street}</td> //only street name shown, if you need to show complete address then you need to iterate over `user.address` object
<td>{user.company.name}</td> //only company name shown, if you need to show complete company name then you need to iterate over `user.name` object
</tr>
)
})
}
return (
<div>
<h1 id="title">API Table</h1>
<table id="users"> //Your Table in post changed to table to make it work
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Address</th>
<th>Company</th>
</tr>
</thead>
<tbody>{renderTable()}</tbody>
</table>
</div>
)
}
Upvotes: 4