Home > database >  React app backend firestore useEffect not working correctly
React app backend firestore useEffect not working correctly

Time:04-24

I am trying to keep track of the number of visitors my website gets using firestore as a backend.

I have two functions in my useEffect hook getVistorCount, and updateVistorCount. getVistorCount gets the doc containing the vistor_count variable from firestore and saves that array of data to state.

My updateVistorCount function gets the id and data of the document I am trying to update from state. The problem is that my state is initialized to an empty array so when I try to get the id and vistor_count from state I get the error "Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'id')" because the array from state is empty.

I am also getting the following warning in VSCode: "React Hook useEffect has missing dependencies: 'numberOfVistors' and 'portfolioStatesRef'. Either include them or remove the dependency array"

Here is the current code:

const portfolioStatesRef = collection(db, "portfolio-stats")
  
  useEffect (() => {

    let sessionKey = sessionStorage.getItem("sessionKey")
    
    const getVistorCount = async () => {
      const dataFromPortfolioStatsCollection = await getDocs(portfolioStatesRef)

      setnumberOfVistors(dataFromPortfolioStatsCollection.docs.map((doc) => {
         return  ({ ...doc.data(), id: doc.id })
      }))
    }

    const updateVistorCount = async () => {

      const portfolioStatsDoc = doc(db, "portfolio-stats", numberOfVistors[0].id)
      const updatedFields = {vistor_count: numberOfVistors[0].vistor_count   1}
      await updateDoc(portfolioStatsDoc, updatedFields)
    }

    getVistorCount()
    
    if (sessionKey === null)
    {
      sessionStorage.setItem("sessionKey", "randomString")  
      updateVistorCount()
    }
    
    }, []) 

CodePudding user response:

Maybe using two effects can achieve what you want. First to get visitors:

useEffect (() => {

    let sessionKey = sessionStorage.getItem("sessionKey")
    
    const getVistorCount = async () => {
      const dataFromPortfolioStatsCollection = await getDocs(portfolioStatesRef)

      setnumberOfVistors(dataFromPortfolioStatsCollection.docs.map((doc) => {
         return  ({ ...doc.data(), id: doc.id })
      }))
    }

    getVistorCount()
    
 }, []) 

Second to update count

useEffect (() => {
    if(!numberOfVistors.length) return;

    const updateVistorCount = async () => {
      const portfolioStatsDoc = doc(db, "portfolio-stats", numberOfVistors[0].id)
      const updatedFields = {vistor_count: numberOfVistors[0].vistor_count   1}
      await updateDoc(portfolioStatsDoc, updatedFields)
   }

   updateVistorCount()
    
 }, [numberOfVistors]) 

  • Related