Pierre Torres
Pierre Torres

Reputation: 287

Cannot display data from firebase with .where()

Hello I'm trying to display data from firebase, it works very well but when I add the condition where() to compare uid to the id present in my database

However in the console.log, it appears well, it's as if between the user request and the getOrders() request; the delay was too short and that he didn't have time to find uid

const [orders, setOrders] = useState([]);
  const [user, setUser] = useState('');

  useEffect( () => {
   fire.auth().onAuthStateChanged((user) => {
      if (user) {
        setUser(user);
        console.log(user);
            } else {
        setUser(null);
      }
    
    });
getOrders();
 
}, []);

 function getOrders() {
    fire.firestore().collection("orders")
    
    .where('uid', '==', `${user.uid}`)
    .where('statut', '==', 'Active')
    .onSnapshot(function (querySnapshot) {
      setOrders(
        querySnapshot.docs.map((doc) => ({
          id: doc.id,
          orderid: doc.data().id,
          statut: doc.data().statut,
          nomproduit: doc.data().nomproduit
          
        }))
      );
    });
  }

enter image description here

Thank you for help.

Upvotes: 0

Views: 39

Answers (1)

fortunee
fortunee

Reputation: 4332

Consider passing the uid as an argument into getOrders() and call it when the user is ready. Like this

const [orders, setOrders] = useState([]);
  const [user, setUser] = useState('');

  useEffect( () => {
   fire.auth().onAuthStateChanged((user) => {
      if (user) {
        setUser(user);
        console.log(user);
        getOrders(user.uid);
            } else {
        setUser(null);
      }
    
    });
}, []);

 function getOrders(uid) {
    fire.firestore().collection("orders")
    
    .where('uid', '==', `${uid}`)
    .where('statut', '==', 'Active')
    .onSnapshot(function (querySnapshot) {
      setOrders(
        querySnapshot.docs.map((doc) => ({
          id: doc.id,
          orderid: doc.data().id,
          statut: doc.data().statut,
          nomproduit: doc.data().nomproduit
          
        }))
      );
    });
  }

Another thing you could do would be to pass user as a dependency into the useEffect() hook like this

useEffect( () => {
   fire.auth().onAuthStateChanged((user) => {
      if (user) {
        setUser(user);
        console.log(user); 
      } else {
        setUser(null);
      }
    
    });
   getOrders();
}, [user]);

This will cause the useEffect to run again when the user has changed. Not the best approach tho, performance wise, just FYI.

Upvotes: 3

Related Questions