Why am I getting a "cannot set property of undefined" when writing to an array generated by a replit.db call?

22 Views Asked by At

This was marked duplicate for some reason. I didn't even know what the thing in the other post was called.

So, my problem is that this replitdb call below (not sure if thats what it's called) somehow sets the users array to {"undefined":{"online":false,"clearance":0}}

var users = {}
db.list().then(keys => {
  for (var i = 0; i < keys.length; i++) {
    db.get(keys[i]).then(value => {
      if (value == null) return
      users[keys[i]] = {online:null,clearance:null}
      users[keys[i]].online = false
      users[keys[i]].clearance = value.clearance // value.clearance is a number between 0 and 5
      
    })
  }
})

This code, again, sets the users array to {"undefined":{"online":false,"clearance":0}} which throws an error when trying to write to a different value that isn't "undefined". The following lines are the lines that cause errors by attempting to write to users[user].

  socket.on('userDisconnect', (user) => {
    users[user].online = false // user is a string
  })
  
  socket.on('userConnect', (user) => {
    users[user].online = true // user is a string
  })

And the error caused from line 260 or when a user attempts to connect to the server is the following:

TypeError: Cannot set property 'online' of undefined

What is going on here, and what am I doing wrong?

0

There are 0 best solutions below