skip to Main Content

I have a table with list of entries and currently I’m fetching data from firestore collection; anytime I add a new document to the list, it appears at the bottom, is there a way to display recently add document on my table at the top instead of the entries appearing at the bottom?

Here’s to code that fetches and displays a new document to my table:-

  useEffect(() =>{
// LISTEN (REALTIME)
const unsub = onSnapshot(
  collection(db, "users"),
  (snapShot) => {
    let list = [];
    snapShot.docs.forEach((doc) => {
      list.push({ id: doc.id, ...doc.data() });
    });
    setData(list);
  },
  (error) => {
    console.log(error);
  }
);

return () => {
  unsub();
};
}, []);

Here’s the code that adds a new document to my table:-

 const handleAdd = async(e) => {
      e.preventDefault();
      // this is the add function to add a new doc
      if(isEmpty(id)){
        await addDoc(collection(db, "users"), {
          ...userInfo,
          timeStamp: serverTimestamp(),
        });    
      } else{
      // this is to update a list 
        await setDoc(doc(db, "users/" + id), {
          ...userInfo,
          timeStamp: serverTimestamp(),
        });    
      }
      navigate("/users")
  }

2

Answers


  1. Chosen as BEST ANSWER

    Here's the solution:-

    In terms of ordering data in a list to show the latest, what you have to do is assign timestamps for all of the documents when they're newly added, then query the data to show the list by the timeStamp either in Ascending or descending order, here's the code to explain that:-

     useEffect(() =>{
        // LISTEN (REALTIME)
        const collectionRef = collection(db, "users");
        const q = query(collectionRef, orderBy("timeStamp", "asc"))
        const unsub = onSnapshot(
          q,
          (snapShot) => {
            let list = [];
            snapShot.docs.forEach((doc) => {
              list = [{ id: doc.id, ...doc.data() }, ...list]
             
            });
            setData(list);
          },
          (error) => {
            console.log(error);
          }
        );
        
        return () => {
          unsub();
        };
        }, []);


  2. Just make new data to come first in the list: by using

    list = [{ id: doc.id, ...doc.data() }, ...list]
    

    whole code

    useEffect(() =>{
    // LISTEN (REALTIME)
    const unsub = onSnapshot(
      collection(db, "users"),
      (snapShot) => {
        let list = [];
        snapShot.docs.forEach((doc) => {
          list = [{ id: doc.id, ...doc.data() }, ...list]
         
        });
        setData(list);
      },
      (error) => {
        console.log(error);
      }
    );
    
    return () => {
      unsub();
    };
    }, []);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search