I am working to a project using ReactNative and FireStore.
I have to render data retrieved from the server.
I do not care about update of the data in short period, I have to retrieve data only one time.
This is the general scenario.
More specifically I want to store fetched data in a state. The render is based on this state. the state, after fetching, should be something like:
list = [{category:"ct1",items:[obj1,obj2,obj3,...]},{category:"ct2",items:[obj1,obj3]}]
If I use the following code Nothing is rendered, in details I have 2 problems.
- the
console.log(list)
show me that list (the state) is empty, butconsole.log(results)
works. - after a while the console show this error: Rendered more hooks than during the previous render.
const [list, setList] = useState([]);
function getData() {
const final = []
const categories = ["ct1", "ct2", "ct3", "ct4"]
var promises = categories.map((category) => {
return db.collection('items')
.where("category", "array- contains", category)
.get()
.then((querySnapshot) => {
const items = [];
querySnapshot.forEach((doc) => {
items.push(doc.data())
});
final.push({
category: category,
items: items
})
})
})
Promise.all(promises).then(function(results) {
console.log("final", final)
//this print [{category:"ct1",items:[obj1,obj2,obj3,...]},{categor
setList(final)
//so I have the final array, I can set the state
console.log("list", list)
//when I call this list is empty
})
};
useEffect(() => {
getData()
}, []);
return ({
list.map((item, index) => (
......
//this function iterate over the list, is very long and works.
//I have tested on a predefined state. So the problem is not this.
))
})