简体   繁体   中英

useEffect with firestore

I'm trying to do the following, i cannot get any errors but what's weird is, while setRivalGuess in the first condition setRivalGuess(doc.data().guess2) doesn't work, the second one setRivalGuess(doc.data().guess1) works really well. I checked database and everything stored well, that is, each data that I want to fetch is available on the database. I don't know whether it is about my way of using useEffect .

const { rivalGuess, setRivalGuess } = useGame(); 
const game = query(roomColRef, where("roomId", "==",  roomId))
useEffect(() => {
    const getUsers = async () => {
        const data = await getDocs(game);
        data.forEach((doc)=> {
            if (doc.data().numberOfPlayers == 2 ){
                if(userValue == doc.data().players[0].username)
                    if (doc.data().guess2 =! 0){
                        setRivalGuess(doc.data().guess2)}
                if (userValue == doc.data().players[1].username) 
                    if (doc.data().guess1 =! 0){ 
                        setRivalGuess(doc.data().guess1)} }})};
    getUsers();
  }, [ rivalGuess, setRivalGuess ])

this works well know...

const UseRivals = (collectionStr) =>{
        const [ rivalGuess,  setRivalGuess ] =useState([])
        const { roomId, userValue } = useGame()
        useEffect(() => {
            const collectionRef = collection(db, collectionStr);
            const q = query(collectionRef, where("roomId", "==", roomId ))
            const unSub = onSnapshot(q , (snapshot) => {
                snapshot.docs.forEach(doc => {
                if (doc.data().numberOfPlayers==2) {
                    if (userValue == doc.data().players[0].username) if (doc.data().guess2 =! 0) 
                     { setRivalGuess(doc.data().guess2) }
                    if  (userValue == doc.data().players[1].username) if  (doc.data().guess1 =! 0)
                        { setRivalGuess(doc.data().guess1)}}})
            }, (err) => {
                console.log(err.message);
            });
            return () => unSub();
        }, [collectionStr]);
    
        return { rivalGuess };
    }
    export default UseRivals;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM