0

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?

0

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.