My issue is very simple. I have a firebase realtime database and i am fetching data from the database and trying to insert in inside a useState so that i can then display this data in my app. But no matter what i do, the data is always undefined or null. Strangely enough if i insert that same exact data inside a jsx component or console log it, it displays without any problem.
Here's what i am doing and a description of the problem:
First here is my realtime-database with users
I simply want to access the fullname property and insert that inside my 'name' state
App.js
const userid = firebase.auth().currentUser.uid
const [usersList , setUsersList ] = useState([])
const [name, setName] = useState(usersList.fullname) //undefined
useEffect(() => {
const usersRef = firebase.database().ref('Users')
let query = usersRef.orderByChild('uid').equalTo(userid);
query.on('value', (snapshot) => {
const users = snapshot.val()
const usersList = []
for (let id in users) {
usersList.push({id, ...users[id]})
}
setUsersList(usersList[0])
})
},[])
Displaying data:
console.log(usersList.fullname) //displays my name perfectly well
And
return (
<div>{usersList.fullname}</div>
)
Also displays perfectly well
But
const [name, setName] = useState(usersList.fullname) //undefined
This seems completely illogical to me! If yo have any insight on why this is happening, share it with me please.