Home > Enterprise >  Get nested data from Firebase v9 in React v18
Get nested data from Firebase v9 in React v18

Time:07-11

My data path in firebase looks like this: Users > rSzP3dXordco4i4EMLORZSYWuyN2 > anime > eFfOzOkqUmIl8acj6lAo Users and anime are collections and id's are documents

The code with which I try to get data are:

const [anime, setAnime]=useState([]);
const [uid, setUid]=useState('')

const fetchAnime = async () => {
  onAuthStateChanged(auth, (user) => {
    if (user) {
      setUid(user.uid)
    } 
  });
  let getAnime = await getDocs(collection(db,"Users", uid,"anime"))
  setAnime(getAnime.docs.map((doc)=>({...doc.data(),id:doc.id})))
}

useEffect(()=>{
fetchAnime()
},[])

I get error code that collection reference must have odd number of segments but I tried multiple ways and for some reason they do not count in the uid. Uid was checked with console log and it fetches it correctly. Once user is created, user document id is copied and is assigned to firestore to have data by user.

CodePudding user response:

The onAuthStateChanged() loads user information asynchronously so your query is mostly running even before the auth state has loaded and hence value of uid is "". Also there's no need to store the UID in state for this unless there's any other use case. Instead your should run the query within onAuthStateChanged() as shown below:

const [anime, setAnime] = useState([]);

useEffect(() => {
  onAuthStateChanged(auth, async (user) => {
    if (user) {
      let getAnime = await getDocs(collection(db, "Users", user.uid, "anime"))
      setAnime(getAnime.docs.map((doc) => ({
        ...doc.data(),
        id: doc.id
      })))
    }
  });
}, [])
  • Related