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

94
Visualizações
Storing the name of the current user and matched user in state using useEffect returning incorrect output

I have a function in my context that takes in two data points, the current username and the username of a randomly selected user who is online

const pairProgrammingMatching = (username, matchedUser) => {
    setPairUsers({username: matchedUser })
}

I call this function in another component using useEffect()

    useEffect((() => {
        console.log('curr username is', username)
        pairProgrammingMatching(username, checkOnlineUsers(pickRandom()).username)
        console.log('inside pairUsers state', pairUsers)
    }), [])

checkOnlineUsers simply returns a list of all users who are currently online and active

let checkOnlineUsers = () => {
    const results = onlineUsers.filter(obj => {
        return obj.profile.is_online === true && obj.profile.currently_active === false && obj.username !== user.username
    })
    return results
}

Here's a sample of what this function returns

[{ email: "***@gmail.com"
   first_name: ""
   last_name: ""
   profile: {city: 'Washington DC', country: 'USA', is_online: true, currently_active: false}
   username: "testingUser" }]

pickRandom simply picks a number between 0 and n, with n being the number of users returned in checkOnlineUsers:

const pickRandom = () => {
    return Math.round(Math.random()*onlineUsers.length)
}

The problem here is that if I print out pairUsers inside my useEffect I expect to see this:

{ 'userA': 'testingUser' }

with userA being the name of the current user. However this is what I get:

{username: undefined}
about 4 years ago · Juan Pablo Isaza
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