I have a users list that is correctly fetched from the API as I can see the records in my console. However, when I try to map it and display it as a table, it doesn't work. This is my component:
interface IUser {
id: number,
email: string,
username: string,
password:string
}
interface UsersProps {
user: IUser[],
url?: string,
loading: boolean
}
const Users: React.FC<UsersProps> = ({
user,
loading,
url
}) => {
const [users, setUsers] = useState<UsersProps>({
user:[],
loading: true,
});
const request: RequestInit = {
method: 'GET',
body: JSON.stringify(user),
headers: {
'Content-Type':'application/json'
}
}
useEffect(() => {
fetch(url, request).then(response => response.json()).then(data => {
setUsers(prev => ({
...prev,
user: [...prev.user, data],
loading:false
}) )
console.log(users.user, "users")
console.log("url", url)
})
}, [])
const getUsers = (u: IUser[]) => {
console.log("users table", u)
return (
<table>
<thead>
<tr>
<th>Id</th>
<th>Username</th>
<th>Email</th>
<th>Password</th>
</tr>
</thead>
<tbody>
{u.map((user, index) =>
<tr key={index}>
<td>{user.email}</td>
<td>{user.password}</td>
<td>{user.username}</td>
</tr>
)}
</tbody>
</table>
)
}
users.user.map((user) => {
console.log("uswe o", user)
})
const rendering = () => {
return (
users.loading ?
<div>Is loading...</div> :
getUsers(users.user)
)
}
//console.log("get users", getUsers(users.user))
return (
<div>
{rendering() }
</div>
)
}
export default Users;
I don't understand what I'm doing wrong, since the values should be displayed.
loadingas props from parent, so any chance there could be another conditionally renderedloadingfrom parent that might be preventing this component to output? Not sure if it's related, the loading message in this component seems to be"Is loading...", but the screenshot seems to be displaying"Loading", which seems to be not matching somehow.