I'm trying to retrieve the array values (areas - 14 elements) from firestore and I want to store it at user defined array
const [documents] = useState([]);
const retrieveAreas = async () => {
try {
await firebase.firestore().collection('Operation').doc(currentid).get()
.then((value) => {
documents.push(
(value.data().areas),
);
});
} catch (e) {
alert(e);
}};
The problem is that when I call documents array I' m receiving all 14 array values together as a only one element in document array. Please help me to retrieve the array values. Thank you.
CodePudding user response:
You are updating the state in wrong way. Refer this article for updating state of React component : https://www.pluralsight.com/guides/manipulating-arrays-and-objects-in-state-with-react
You are using Push operation that is for pushing single object in array while your use case is something in which you are receiving array in response. So you need to concat that response in documents state.
and use following snippet
const [documents, setDocuments] = useState([]);
const retrieveAreas = async () => {
try {
await firebase.firestore().collection('Operation').doc(currentid).get()
.then((value) => {
if(value){
const apiData = value.data().areas
const newDocuments = [...documents,...apiData]
setDocuments(newDocuments)
}
});
} catch (e) {
alert(e);
}
};