I am new to React, but I struggle to find the error in what I am writing.
The objective is to show a list of users, asking it to a server via socket.io
. My original code is as follows:
// the list of users
const [users, setUsers] = useState()
useEffect(() => {
if (socket == null) return
// listen once to the get user event
socket.once('load-users', userList => {
console.log('received type', typeof(userList), ':', userList)
setUsers(userList)
})
console.log('emitting get users')
// ask the server for the users
socket.emit('get-users', {all: true})
}, [socket, users])
When rendering the component I wanted to return a simple list:
return (
<ul>
{users.map((user) => <li key={user.name}>{user.name} | {user.password}</li>)}
</ul>
)
This gives me an ominous error in the browser:
Compiled with problems:
×
ERROR
undefined is not a function (near '...users.map...')
Dashboard@http://localhost:3000/static/js/bundle.js:184:24
...
After some hours struggling I tried to initialize the state to an array
const [users, setUsers] = useState([])
And lo and behold, it works! The real problem is that I don’t know why.
Why is the initial type of the state so important? Why setState
can’t change it?