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

103
Vistas
find method returns undefined

I make find method on users array but selectedUserId = undefined How can I execute this method necessarily after the async function so that the selectedUserId is not undefined?

function App() { 
const [selectedUserId, setSelectedUserId] = useState(null)
const [users,setUsers] = useState([])
const [loading, setLoading] = useState(false)
console.log(users)

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

 const selectedUser = users.find(u => u.id === selectedUserId)
 console.log(selectedUser)

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

if(loading) {
  return <img src={preloader} alt="preloader"/>
} 

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

useEffect() hook will be called after rendering / component update. so, on First time the users value will be empty array.

so, the selectedUser value will be undefined. Wrap it in another useEffect will work.

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