Dodo1991
Dodo1991

Reputation: 21

Apparently no causes for the error "TypeError: Cannot read properties of undefined "

I have to show in the layout some data I take from a database. Here is the code I use to fetch the data:

    const [array, setArray] = useState([])
    const collectionRef = collection(db, "Collection")
    const q = query(collectionRef, orderBy("Order", "desc"))

    useEffect(() => {
      auth.onAuthStateChanged(function (user) {
      if (user) {
             onSnapshot(q, (data) =>
             setArray(data.docs.map((doc) => ({ ...doc.data(), id: doc.id })))
         );
      }
    })
   }, [auth]);

Below is the html

    <div> 
        <h2>{array[0].Name}</h2>
    </div>

What baffles me most is that the error does not always show up, sometimes everything works and sometimes it stops working without apparent causes. If I do console.log of the array sometimes it prints the data and everything works, sometimes it prints an empty array and does nothing. I state that that array is never modified, it is loaded at the beginning of the code and the data is only read.

Upvotes: 1

Views: 582

Answers (1)

assembler
assembler

Reputation: 3300

array is empty for the first render and for all the other renders until the data is returned. Try something like:

<div> 
    <h2>{array.length && array[0].Name}</h2>
</div>

Upvotes: 1

Related Questions