Home > front end >  Unable to perform push on array in NextJs
Unable to perform push on array in NextJs

Time:11-21

I am currently working on a social media app for learning and I got stuck in NextJs ServerSide Rendering.

export async function getServerSideProps() {
  const fetchedProjects = []

  const data = onSnapshot(query(collection(db, 'projects')), snapshot => {
    fetchedProjects.push(snapshot.docs[0]);
  })
  data();

  return {
    props: {
      projects: JSON.stringify(fetchedProjects)
    }
  }
}

the snapshot.docs[0] returns an Object and I am trying to push it into the fetchedProjects array, but it returns me an empty array every time. I tried multiple ways of doing it but it doesn't work like using await onSnapshot.

CodePudding user response:

onSnapshot attaches a realtime listener to the database, which first gets the current data and then continues listening for changes. This means that it can be invoked multiple times, which is why it doesn't return a promise and can't be use with await or as the result of an async method: those all expect only a single result.

To return a result from the async method, use getDocs instead of onSnapshot.

export async function getServerSideProps() {
  const snapshot = await getDocs(query(collection(db, 'projects'));
  const fetchedProjects = [snapshot.docs[0]]

  return {
    props: {
      projects: JSON.stringify(data)
    }
  }
}

Also see the Firebase documentation on getting multiple documents from a collection once.

  • Related