I fetched some data from my firebase realtime database which is returned as an object inside my useEffect hook function. I wanted to map these data into different rows in my UI. But the problem is when I try to setState in the component by passing the fetched data in the setState() function, it returns an empty object. I tried to convert the fetched data object to convert to an array and then set the state, still, the console.log(state) shows an empty array. When I use the state as a dependency (2nd argument in the useEffect) it returns an infinite loop of the state. The code looks like this-
const ToDoList = () => {
const [toDo, setToDo] = useState([])
useEffect(() => {
const fetchData = async () => {
try{
toDoListRef.on('value', snapshot => {
const fetchedPostObject = snapshot.val()
console.log(fetchedPostObject) // shows fetched data in the object form
var fetchedPostArr = []
fetchedPostArr = Object.entries(fetchedPostObject)
setToDo(fetchedPostArr)
console.log(toDo) // []
})
}catch(err){
console.log(err)
}
}
fetchData()
}, [])
}
if I don't convert the fetched object to an array then it returns an empty object if again I use the dependency, it returns an infinite state.