Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

105
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda