Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

96
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!