TypeError: Cannot read property ‘1’ of undefined everytime I’ll reload the webpage

Getting the users collection from firestore:

const [users, setUsers] = useState([])
 useEffect(() => {
        if (currentUser) {
          const unsubscribe = db
            .collection("users")
            .doc(uid)
            .onSnapshot((snapshot) => {
          const arr = [];
          arr.push({
            ...snapshot.data(),
          });

          setUsers(arr);
        });

      return () => {
        unsubscribe();
      };
    }
  }, [currentUser]);

I can already retrieve the data with this:

 const userItems1 = users[0][1]?.items;
 let ar = [];
 for (const [key, value] of Object.entries(userItems1)) {
 ar.push(key, " ");

and then display the data in the screen with this:

<li>{ar}</li>

All is well, however, it has an error every time I’ll reload the webpage

TypeError: Cannot read property ‘1’ of undefined

Does it have something to do with currentUser?

I’m getting the currentUser from my useSelector:

const mapState = ({ user }) => ({
  currentUser: user.currentUser,
});

 const { currentUser } = useSelector(mapState);

Any idea on how to fix this? Thank you

Answer

useEffect runs after the first render, not before it and your state is []

It would be similar when you are executing this:

[][0][1]

Try to place some conditions before you execute them like:

const userItems1 = users[0]?.[1]?.items;
 if (userItems1) {
 let ar = [];
 for (const [key, value] of Object.entries(userItems1)) {
 ar.push(key, " ");
}

Also to check your arr before rendering it, because it will be undefined in the initial render:

{ar && <li>{ar}</li>}