Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

178
Vistas
Why do I have undefined in selectedUser?

Why do I have undefined in selectedUser? After all, I go through the find method through the users array and the first id of the users array should be written to selectedUser

function App() { 
const [selectedUserId, setSelectedUserId] = useState(null)
const [users,setUsers] = useState([])
const selectedUser = users.find(u => u.id === selectedUserId)
console.log(users)
console.log(selectedUser)

useAsyncEffect(async () => {
  const res = await fetch('https://jsonplaceholder.typicode.com/users')
  const data = await res.json()
  setUsers(data)
}, [])

const onUserClick = (userId) => {
  setSelectedUserId(userId)
}

return (
  <div>
  { selectedUser ? <ListUsers users={users} onUserClick={onUserClick} /> : <Profile user= 
 {selectedUser}  />
  }
  </div>
)
}
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You can use a loading state to determine when the async function is done and only then you can set the selected user. Otherwise, it remains set to 'null' when the 'return' is rendered.

Below is pseudo code.

 function App() { 
    const [selectedUserId, setSelectedUserId] = useState(null)
    const [users,setUsers] = useState([])
    const selectedUser = users.find(u => u.id === selectedUserId)
    const [loading, setLoading] = useState(false)

    console.log(users)
    console.log(selectedUser)
    
    useAsyncEffect(async () => {
      setLoading(true)
      const res = await fetch('https://jsonplaceholder.typicode.com/users')
      const data = await res.json()
      setUsers(data)
      setLoading(false)
    }, [])
    
    const onUserClick = (userId) => {
      setSelectedUserId(userId)
    }
   if (loading){
      return "Loading..."
      // you can use a nicer loader component here
   }
    
    return (
      <div>
      { selectedUser ? <ListUsers users={users} onUserClick={onUserClick} /> : <Profile user= 
     {selectedUser}  />
      }
      </div>
    )
    }
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda