0

I am trying to view or retrieve all the contents of the array in my collection, I am using reactjs and firebase this is my code

async function getData(){
  const productreference = collection(firestoredb, "Orders",`${userID}`,"Orderlist" );
  const q = query(productreference);
  onSnapshot(q,(snapshot) => 
    console.log(snapshot.docs.map((doc) => ({ ...doc.data().Data })))
  )
}

result

If I try this

async function getData(){
  const productreference = collection(firestoredb, "Orders",`${userID}`,"Orderlist" );
  const q = query(productreference);
  onSnapshot(q,(snapshot) => 
    console.log(snapshot.docs.map((doc) => ({ ...doc.data().Data[0] })))
  )
}

it will just show the entire content of the array 0 per document

This is my database structure:

database structure

This what I did

const [data, setData] = useState([]);
async function getData(){
  const productreference = collection(firestoredb, "Orders",`${userID}`,"Orderlist" );
  const q = query(productreference);
  onSnapshot(q,(snapshot) => 
    setData(snapshot.docs.map((doc) => ({ ...doc.data().Data })))
  )
  console.log(data)
}

this is the result of the console.log results

so how can i show the content of the "Data" per document

jnpdx
  • 45,847
  • 6
  • 64
  • 94
Cognitow
  • 1
  • 1
  • Oh sorry, I fixed it thank you – Cognitow Feb 07 '22 at 09:57
  • I **strongly** recommend to start with the Realtime Database if you are a noob. – Junaga Feb 07 '22 at 10:01
  • I use the Realtime Database to store users credentials – Cognitow Feb 07 '22 at 10:07
  • I'm not sure I understand what the problem is that you're asking our help with. Can you edit your question to clarify what isn't working about the code you shared? – Frank van Puffelen Feb 07 '22 at 14:24
  • Oh sorry I need to retrieve the array from "Data" and store it in a const [data,setData]=useState([]), when i do this setData(doc.data().Data[]); and console.log(data), i get a undefined – Cognitow Feb 07 '22 at 15:40
  • 1
    `onSnapshot` is *asynchronous*. You can't call `console.log` on the next line outside of the closure and have it reflect the data set *inside* the callback that is reached asynchronously. In addition, `setState` is asynchronous as well. Using `setState` and then `console.log` immediately afterwards will not show the most recently set data. – jnpdx Feb 07 '22 at 16:31
  • Does this answer your question? [How to return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – Phix Feb 07 '22 at 16:33
  • Oh okay thank you for that. I am using the console.log as a checker, to check if the data has been set, because i need to map the contents of the "Data" per document but somehow when I map the contents of Data it does not show it contents – Cognitow Feb 07 '22 at 16:56

0 Answers0