I am trying to get the name of a user based on the user id, using a .map()
method. The code that I wrote seems good to me, however, I get the error mentioned in the question title and the page won’t render.
See the image below:
Here’s an image of the error stack:
And here’s the code I have:
JavaScript
x
72
72
1
import { SearchBox } from "../SearchBox"
2
import { StyledNavBar, NavSection, StyledLink, StyledLogo } from "./styles"
3
import logo from './Logo2.png'
4
import { useDispatch } from "react-redux"
5
import { useHistory } from "react-router"
6
import axios from "axios"
7
import { useEffect, useState } from "react"
8
9
function useApi() {
10
const userId = localStorage.getItem('userId')
11
const dispatch = useDispatch()
12
const [UserNames, setUserNames] = useState()
13
14
useEffect(() => {
15
async function getData() {
16
try {
17
const { data } = await axios({
18
method: 'GET',
19
baseURL: process.env.REACT_APP_SERVER_URL,
20
url: '/users'
21
})
22
console.log(data)
23
dispatch(setUserNames(data))
24
}catch(error){
25
dispatch(console.log(error))
26
}
27
}
28
29
getData()
30
31
}, [])
32
33
return { userId, UserNames }
34
}
35
36
37
export const NavBar = function({}) {
38
const { userId, UserNames } = useApi()
39
console.log(UserNames)
40
const token = localStorage.getItem('token')
41
const dispatch = useDispatch()
42
const history = useHistory()
43
44
function handleClick(){
45
46
dispatch({type: 'USER_LOGOUT'})
47
localStorage.clear()
48
history.push('/')
49
}
50
51
return(
52
<StyledNavBar>
53
<NavSection>
54
{!token && <StyledLink to='/login'>Ingresar</StyledLink>}
55
{!token && <StyledLink to='/signup'>Registrarse</StyledLink>}
56
<StyledLink to='/'>Categorías</StyledLink>
57
<StyledLink to='/'><StyledLogo src={logo} /></StyledLink>
58
{token && <StyledLink to='/'>Mis Transacciones</StyledLink>}
59
{token && <StyledLink to='/sellproduct'>Vender</StyledLink>}
60
{!!UserNames && UserNames.length > 0 && UserNames.map((usr, i) => {
61
return usr[i]._id === userId ?
62
<p>{usr[i].name}</p>
63
:
64
''
65
})}
66
<SearchBox />
67
{token && <button type='button' onClick={handleClick}>Cerrar Sesión</button>}
68
</NavSection>
69
</StyledNavBar>
70
)
71
}
72
So it’s pretty much telling me that the usr[i]._id
line is not correct, but as far as I can see nothing is wrong with that code.
Advertisement
Answer
I think you might just want usr and not usr[i]? The map() gives you the individual item from the iterable.