0

I have the following code in the component: I am not able to get an updated state.

When I call createUserList I can see the users in UserList component but in UserComponet when I log users I can not see users there.

The code I am using :

function UserComponent() {
    const [users, setUsers] = useState<any>([])


  const register = () => {
    userAgent.delegate = {
      onMessage(message: Message) {
        let usernameList = message.event.entry
        if (message.event['@_category'] === 'activate') {
          createUserList(usernameList); 
        } else if (message.event['@_category'] === 'de-activate') {
          
          // empty user list but I can see users in react dev tools
          console.log(users)
          const username = message.event.entry
          removeUser(username)
        }
      }
    }
  }

  const createUserList = (usernameList: any) => {
    let userList: any = []
    usernameList.forEach((user: any) => {
      userList.push({'uri': user['@_uri'], 'name': user['@_uri'].substr(10, 8)})
    })

    // here I can see updated userList
    console.log(userList)
    setUsers(userList)
    setTimeout(() => {

      // users is empty here
      console.log(users)
    }, 5000)
  }

  return (
    <UserList users={users}/>
  )

}

function UserList({users}) {
    return (
        <div>
            {users.map((user) => <h2>user</h2>)}
        </div>
    )
}
Rushikesh Koli
  • 23
  • 1
  • 1
  • 6
  • What and where is calling `bcd` function? Can you update your question to include a more comprehensive code example? – Drew Reese Apr 14 '21 at 08:00
  • ```bcd``` gets called initially and then I am using it for WebSocket event... so when I receive a particular event I call ```bcd``` – Rushikesh Koli Apr 14 '21 at 08:03
  • I could see the updated state in react dev tools. – Rushikesh Koli Apr 14 '21 at 08:03
  • Updating state is asynchronous, so if you log the state immediately after updating it, you will see the old value (but the state will still update) –  Apr 14 '21 at 08:04
  • I also did try with the timeout function after setting state.. but when I try to log in timeout function I am getting an old empty array.. – Rushikesh Koli Apr 14 '21 at 08:07
  • Right, as this is how javascript closures generally work. I suspect you are simply using a stale enclosure, but until you share what you are actually doing there's not much use in speculation. – Drew Reese Apr 14 '21 at 08:08
  • @DrewReese Hey I posted the code below.. – Rushikesh Koli Apr 14 '21 at 08:42

0 Answers0