My component looks like this:
import axios from "axios";
import React, { useState, useEffect } from "react";
import { Link } from 'react-router-dom'
import User from "./User";
const Users = () => {
const [users, setUsers] = useState([])
useEffect(() => {
axios("http://localhost:8000/users")
.then(response => setUsers(...response.data)})
.catch(error => console.log(error))
}, [users])
return (
<>
<h1>All users</h1>
<button className="btn btn-primary mb-2"><Link to="/users/create">Create</Link></button>
<table className="table table-striped">
<thead>
<tr>
<th scope="col">Name</th>
<th scope="col"></th>
<th scope="col">Created</th>
<th scope="col">Role</th>
<th scope="col">Action</th>
</tr>
</thead>
<tbody>
{users && users.map( user => <User user={user} key={user.id}/>)}
</tbody>
</table>
</>
);
}
export default Users;
When I refresh the page, I see the following error in the console
index.js:37 Uncaught TypeError: users.map is not a function
Note: if I log the users state in the console I can see the correct data.
What is wrong with my component?
Get rid of the ...
- you're splatting the response data array to multiple arguments, while setState only accepts one.
That means your users won't be an array, but just the first user.
Also get rid of the [users]
dependency to avoid the infinite loop - just make it []
.