Funcion map
Publicado por Franco (1 intervención) el 24/09/2020 18:24:42
Hola! Tengo el siguiente desafío, alguien me podría ayudar a encontrar el error?!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import React from 'react';
const TOTAL_USERS = 5
const Exercise01 = () => {
const [users, setUsers] = React.useState([])
/* THE FIX STARTS HERE */
React.useEffect(() => {
for(var i = 1; i < TOTAL_USERS; i++) {
// We fetch the user
fetch('https://jsonplaceholder.typicode.com/users?id=' + i)
.then(r => r.json()) // converts response to obj
.then(user => user[0]) // maps [{..}] to {..} since the API provides an array
.then(user => {
setUsers([
...users,
user
])
})
}
}, [])
/* THE FIX ENDS HERE */
return (
<div className="container">
<h2>Instructions</h2>
<p>We are currently trying to render the first 5 users we obtain from a REST API. The problem is that, for some reason, it's only rendering one of them. Another thing we've noticed is that, sometimes, it renders different user.</p>
<p>
<strong>TODO:</strong>
<ul>
<li>Fetch and Render the first 5 users</li>
<li>Make sure the order is ascendant by ID</li>
</ul>
</p>
<hr className="my-5" />
<h3>Users</h3>
<ul className="list-group">
{users.map(user => <li key={`user-${user.id}`} className="list-group-item">
<strong>ID:</strong> {user.id} - <strong>Name:</strong> {user.name} <strong>Email:</strong> {user.email}
</li>)}
</ul>
</div>
);
};
export default Exercise01;
Valora esta pregunta
0