Skip to content
Advertisement

TypeError: Cannot read property ‘_id’ of undefined ReactJs?

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:

enter image description here

Here’s an image of the error stack:

enter image description here

And here’s the code I have:

import { SearchBox } from "../SearchBox"
import { StyledNavBar, NavSection, StyledLink, StyledLogo } from "./styles"
import logo from './Logo2.png'
import { useDispatch } from "react-redux"
import { useHistory } from "react-router"
import axios from "axios"
import { useEffect, useState } from "react"

function useApi() {
  const userId = localStorage.getItem('userId')
  const dispatch = useDispatch()
  const [UserNames, setUserNames] = useState()

  useEffect(() =>  {
    async function getData() {
      try {
        const { data } = await axios({
        method: 'GET',
        baseURL: process.env.REACT_APP_SERVER_URL,
        url: '/users'
        })
        console.log(data)
        dispatch(setUserNames(data))
      }catch(error){
        dispatch(console.log(error))
      }
    }
    
    getData()
    
  }, [])

  return { userId, UserNames }
}


export const NavBar = function({}) {
  const { userId, UserNames } = useApi()
  console.log(UserNames)
  const token = localStorage.getItem('token')
  const dispatch = useDispatch()
  const history = useHistory()

  function handleClick(){

    dispatch({type: 'USER_LOGOUT'})
    localStorage.clear()
    history.push('/')
  }

  return(
    <StyledNavBar>
      <NavSection>
        {!token && <StyledLink to='/login'>Ingresar</StyledLink>}
        {!token && <StyledLink to='/signup'>Registrarse</StyledLink>}
        <StyledLink to='/'>Categorías</StyledLink>
        <StyledLink to='/'><StyledLogo src={logo} /></StyledLink>
        {token && <StyledLink to='/'>Mis Transacciones</StyledLink>}
        {token && <StyledLink to='/sellproduct'>Vender</StyledLink>}
        {!!UserNames && UserNames.length > 0 && UserNames.map((usr, i) => {
          return usr[i]._id === userId ?
            <p>{usr[i].name}</p>
          :
            ''
        })}
        <SearchBox />
        {token && <button type='button' onClick={handleClick}>Cerrar Sesión</button>}
      </NavSection>
    </StyledNavBar>
  )
}

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.

Answer

I think you might just want usr and not usr[i]? The map() gives you the individual item from the iterable.

Advertisement