Reputation: 1222
I'm trying to fill an empty state array with the elements of a Firebase database
retrieveCategories = async () => {
const { categories } = this.state;
const { eventTypes } = constants;
let count = eventTypes;
const snapshot = await firebase.database().ref('/categories').once('value');
while (count !== -1) {
const cat = snapshot.val()[count];
this.setState(prevState => ({ categories: [...prevState.categories, cat] }));
count -= 1;
}
console.log(categories);
}
The problem is that no matter what I do, the array does not update itself, proven when the console.log(categories);
only throws a []
.
What can I do to solve this issue?
Upvotes: 0
Views: 35
Reputation: 325
You can do it like this
let {categories} = this.state
categories.push(cat)
this.setState({categories})
Also console.log(this.state.categories) because the state is updated after this.setState.
Upvotes: 1