I want to fetch 3 different things from firestore, hence have applied 3 useEffect in my code, out of which my react is not reading the map function inside 3rd useEffect. Here this map function in 3rd useEffect is not working
Code:
1st useEffect:
useEffect(() => {
var applications = [];
const hospitals = [];
const studentId = [];
const details = [];
firebaseConfig
.firestore()
.collection("counselor")
.doc(currentUser.uid)
.collection("studentDetails")
.get()
.then((snapshot) => {
snapshot.docs.forEach((detail) => {
let currentID = detail.id;
let appObj = { ...detail.data(), ["id"]: currentID };
details.push(appObj);
details.push(detail.data());
});
setDetails(details);
});
}, []);
2nd useffect:
useEffect(() => {
const item = [];
details.map((detail) => {
console.log(detail.id);
firebaseConfig
.firestore()
.collection("counselor")
.doc(currentUser.uid)
.collection("studentDetails")
.doc(detail.id)
.collection("studentApplications")
.get()
.then((snapshot) => {
snapshot.docs.forEach((detail) => {
let currentID = detail.id;
let appObj = { ...detail.data(), ["id"]: currentID };
item.push(detail.data().applicationStatus);
setStudentId(item);
});
});
});
setDemo(item);
}, [details]);
3rd useeffect:
useEffect(() => {
demo.map((hii) => {
if (hii === "PaymentFormFilled") {
complete = complete + 1;
setCom(complete);
}
});
}, [demo]);
Your error is not clear: "react is not reading the map function...".
There could be several issues:
Is setDemo assigning a value to a state variable called demo? If not, your 3rd useEffect won't be triggered
What is the value assigned to demo? You might not run .map on it
Because setCom is async. state complete only update value when component re-render. Please move setCom to the outside loop. And using forEach instead map in this case.
useEffect(() => {
let newCount = complete;
demo.forEach((hii) => {
if (hii === "PaymentFormFilled") {
newCount += 1;
}
});
setCom(newCount);
}, [demo]);
Related
I am trying to refactor my code to work solo with firebase the issue that I am facing is firebase methods for example onSnapshot, could this method totally replace the need for the classic first data fetch ? I am ruining in to bunch of run time errors since many data are not available at start and I am starting to doubt my onSnapShot, below is the code to my entry component where most of the data fetching using onSnapShot happens but still many values at start are undefined any idea how to tackle such issue ? the data are there but at start they are not,
useEffect(() => {
context.SetUser('trainer');
const fetchClient = () => {
const colReClients = collection(db, 'Clients');
const id: string = _authContext?.currentUser?.uid;
const unsub = onSnapshot(doc(colReClients, id), (doc) => {
console.log(doc.data(), 'snapShot triggered');
///////////// Refactor to foreach
context.SetExerciseStateBackEnd('dataCenter', doc.data()?.clients);
//context.SetExerciseStateBackEnd('focus', doc.data()?.focus);
});
return () => unsub();
};
if (_authContext?.currentUser) {
fetchClient();
}
}, [_authContext?.currentUser?.uid]);
useEffect(() => {
const fetchWeeks = async () => {
// ADD WEEKS
// Weeks Collection Reference
const colRefWeeks = collection(db, 'Weeks');
const docRefWeeks = doc(colRefWeeks, `${context.focus}`);
const unsub = onSnapshot(docRefWeeks, (doc) => {
console.log(doc.data(), 'snapShot triggered');
context.SetExerciseStateBackEnd('weeks', { [`${context.focus}`]: doc.data()?.clientWeeks });
const arr = doc.data()?.clientWeeks.find((el: any) => el.weekId === context.weekFocus).routines;
if (arr) {
context.SetExerciseStateBackEnd('routines', arr);
}
});
return () => unsub();
};
fetchWeeks();
}, [context.focus]);
I'm trying to make a Tweets Application with React and Firebase and I have been suffering when trying to get info from more than 1 collection.
So this is the story:
I get the tweets using onSnapshot. All fine here
I need more info from 2 other collections: user_preferences and user_photo, so I use .get() within the onSnapshot
For managing asynchronism, I resolve my 2 promises before returning the tweet data + details data object for my map function.
I made a console.log of my mappedTweet and the values are OKEY. Here I can see the tweet data + details data
But my STATE "tweets" just have an array of undefined objects =(. It shows the right number of rows accoroding to my Tweets collection but rows of undefined data, and not the rows of my mappedTweets objects. Why?
Can anyone shed some light?
useEffect(() => {
//------------getting the TWEETS with onSnapshot()-------------
const cancelSuscription = firestore
.collection('tweets')
.onSnapshot((snapshot) => {
const promises = [];
const tweetsMapped = snapshot.docs.map((doc) => {
let tweetAndAuthor;
const tweetMappped = {
text: doc.data().text,
likes: doc.data().likes,
email: doc.data().email,
created: doc.data().created,
uid: doc.data().uid,
id: doc.id,
};
let authorPreference, authorPhoto;
const userPreferencePromise = firestore
.collection('user_preferences')
.where('uid', '==', tweetMappped.uid)
.get();
const userPhotoPromise = firestore
.collection('user_photos')
.where('id', '==', tweetMappped.uid)
.get();
promises.push(userPreferencePromise);
promises.push(userPhotoPromise);
//------------getting the AUTHOR USER PREFERENCES with .get()-------------
userPreferencePromise.then((snapshot2) => {
authorPreference = snapshot2.docs.map((doc) => {
return {
username: doc.data().username,
color: doc.data().color,
};
});
});
//------------getting the AUTHOR PHOTO with .get()-------------
userPhotoPromise.then((snapshot3) => {
authorPhoto = snapshot3.docs.map((doc) => {
return {
photoURL: doc.data().photoURL,
};
});
});
Promise.all(promises).then((x) => {
return {
...tweetMappped,
author: authorPreference[0].username,
authorColor: authorPreference[0].color,
authorPhoto: authorPhoto[0].photoURL,
};
});
});
Promise.all(promises).then((x) => {
setTweets(tweetsMapped);
});
});
return () => cancelSuscription();
}, []);
Well, I made it work by changing the model I was using to retrieve the data from Firebase.
I was using an outer onSnapshot with nested promises (I think I was very near here), but now I'm using nested onSnapshots and now app is behaving as expected.
So this is the new useEffect
useEffect(() => {
let cancelUserPrefSuscription, cancelUserPhotoSuscription;
// First onSnapshot
const cancelTweetSuscription = firestore
.collection('tweets')
.onSnapshot((tweetSnapshot) => {
const list = [];
tweetSnapshot.docs.forEach((tweetDoc) => {
//Second onSnapshot
cancelUserPrefSuscription = firestore
.collection('user_preferences')
.where('uid', '==', tweetDoc.data().uid)
.onSnapshot((userPrefSnapshot) => {
userPrefSnapshot.docs.forEach((userPrefDoc) => {
//Third onSnapshot
cancelUserPhotoSuscription = firestore
.collection('user_photos')
.where('id', '==', tweetDoc.data().uid)
.onSnapshot((userPhotoSnapshot) => {
userPhotoSnapshot.docs.forEach((userPhotoDoc) => {
//Taking the whole data i need from all snapshots
const newData = {
id: tweetDoc.id,
...tweetDoc.data(),
author: userPrefDoc.data().username,
authorColor: userPrefDoc.data().color,
authorPhoto: userPhotoDoc.data().photoURL,
};
list.push(newData);
//Updating my state
if (tweetSnapshot.docs.length === list.length) {
setTweets(list);
}
});
});
});
});
});
});
return () => {
cancelTweetSuscription();
cancelUserPrefSuscription();
cancelUserPhotoSuscription();
};
}, []);
Edit: Fix from comments of above code
Author: #samthecodingman
For each call to onSnapshot, you should keep track of its unsubscribe function and keep an array filled with the unsubscribe functions of any nested listeners. When an update is received, unsubscribe each nested listener, clear the array of nested unsubscribe functions and then insert each new nested listener into the array. For each onSnapshot listener attached, a single unsubscribe function should be created that cleans up the listener itself along with any nested listeners.
Note: Instead of using this approach, create a Tweet component that pulls the author's name and photo inside it.
useEffect(() => {
// helper function
const callIt = (unsub) => unsub();
// First onSnapshot
const tweetsNestedCancelListenerCallbacks = [];
const tweetsCancelListenerCallback = firestore
.collection('tweets')
.onSnapshot((tweetSnapshot) => {
const newTweets = [];
const expectedTweetCount = tweetSnapshot.docs.length;
// cancel nested subscriptions
tweetsNestedCancelListenerCallbacks.forEach(callIt);
// clear the array, but don't lose the reference
tweetsNestedCancelListenerCallbacks.length = 0;
tweetsNestedCancelListenerCallbacks.push(
...tweetSnapshot.docs
.map((tweetDoc) => { // (tweetDoc) => Unsubscribe
const tweetId = tweetDoc.id;
//Second onSnapshot
const userPrefNestedCancelListenerCallbacks = [];
const userPrefCancelListenerCallback = firestore
.collection('user_preferences')
.where('uid', '==', tweetDoc.data().uid)
.limitToFirst(1)
.onSnapshot((userPrefSnapshot) => {
const userPrefDoc = userPrefSnapshot.docs[0];
// cancel nested subscriptions
userPrefNestedCancelListenerCallbacks.forEach(callIt);
// clear the array, but don't lose the reference
userPrefNestedCancelListenerCallbacks.length = 0;
//Third onSnapshot
const userPhotoCancelListenerCallback = firestore
.collection('user_photos')
.where('id', '==', tweetDoc.data().uid)
.limitToFirst(1)
.onSnapshot((userPhotoSnapshot) => {
const userPhotoDoc = userPhotoSnapshot.docs[0];
// Taking the whole data I need from all snapshots
const newData = {
id: tweetId,
...tweetDoc.data(),
author: userPrefDoc.data().username,
authorColor: userPrefDoc.data().color,
authorPhoto: userPhotoDoc.data().photoURL,
};
const existingTweetObject = tweets.find(t => t.id === tweetId);
if (existingTweetObject) {
// merge in changes to existing tweet
Object.assign(existingTweetObject, newData);
if (expectedTweetCount === newTweets.length) {
setTweets([...newTweets]); // force rerender with new info
}
} else {
// fresh tweet
tweets.push(newData);
if (expectedTweetCount === newTweets.length) {
setTweets(newTweets); // trigger initial render
}
}
});
userPrefNestedCancelListenerCallbacks.push(userPhotoCancelListenerCallback);
});
// return an Unsubscribe callback for this listener and its nested listeners.
return () => {
userPrefCancelListenerCallback();
userPrefNestedCancelListenerCallbacks.forEach(callIt);
}
})
);
});
// return an Unsubscribe callback for this listener and its nested listeners.
return () => {
tweetsCancelListenerCallback();
tweetsNestedCancelListenerCallbacks.forEach(callIt);
};
}, []);
Edit: Splitting the code in two components
Note: Changed limitToFirst(1) --> limit(1). Splitting the fetch logic in two components simplified the onSnapshot approach!
1.The Parent Component
useEffect(() => {
const tweetsUnsubscribeCallback = firestore
.collection('tweets')
.onSnapshot((tweetSnapshot) => {
const mappedtweets = tweetSnapshot.docs.map((tweetDoc) => {
return {
id: tweetDoc.id,
...tweetDoc.data(),
};
});
setTweets(mappedtweets);
});
return () => tweetsUnsubscribeCallback();
}, []);
2.The Child Component: Tweet
useEffect(() => {
// Helper Function
const unSubscribe = (unsub) => unsub();
//------------getting the AUTHOR USER PREFERENCE
const userPrefNestedUnsubscribeCallbacks = [];
const userPrefUnsubscribeCallback = firestore
.collection('user_preferences')
.where('uid', '==', tweet.uid)
.limit(1)
.onSnapshot((userPrefSnapshot) => {
userPrefNestedUnsubscribeCallbacks.forEach(unSubscribe); // cancel nested subscriptions
userPrefNestedUnsubscribeCallbacks.length = 0; // clear the array, but don't lose the reference
//------------getting the AUTHOR PHOTO
const userPhotoUnsubscribeCallback = firestore
.collection('user_photos')
.where('id', '==', tweet.uid)
.limit(1)
.onSnapshot((userPhotoSnapshot) => {
// Taking the whole data I need from all snapshots
setAuthor({
author: userPrefSnapshot.docs[0].data().username,
authorColor: userPrefSnapshot.docs[0].data().color,
authorPhoto: userPhotoSnapshot.docs[0].data().photoURL,
});
});
userPrefNestedUnsubscribeCallbacks.push(userPhotoUnsubscribeCallback);
});
return () => {
userPrefUnsubscribeCallback();
userPrefNestedUnsubscribeCallbacks.forEach(unSubscribe);
};
}, []);
Basically, you've pushed the promises to your promise array in the state they were before you you processed their data. You want to make use of the Promise.all(docs.map((doc) => Promise<Result>)) pattern here where each document should return a single Promise containing its final result. This then means that the Promise.all will resolve with Result[].
Note: If inside a Promise you are mutating a variable outside of the Promise (e.g. pushing to an array), that is generally a sign that you are doing something wrong and you should rearrange your code.
Here's a quick example of throwing this together:
useEffect(() => {
let unsubscribed = false;
//------------getting the TWEETS with onSnapshot()-------------
const cancelSuscription = firestore
.collection('tweets')
.onSnapshot((snapshot) => {
const tweetsMappedPromises = snapshot.docs.map((doc) => {
let tweetAndAuthor;
const tweetMappped = {
text: doc.data().text,
likes: doc.data().likes,
email: doc.data().email,
created: doc.data().created,
uid: doc.data().uid,
id: doc.id,
};
//------------getting the AUTHOR USER PREFERENCES with .get()-------------
const userPreferencePromise = firestore
.collection('user_preferences')
.where('uid', '==', tweetMappped.uid)
.limitToFirst(1)
.get()
.then((prefDocQuerySnapshot) => {
const firstPrefDoc = photoDocQuerySnapshot.docs[0];
const { username, color } = firstPrefDoc.data();
return { username, color };
});
//------------getting the AUTHOR PHOTO with .get()-------------
const userPhotoPromise = firestore
.collection('user_photos')
.where('id', '==', tweetMappped.uid)
.limitToFirst(1)
.get()
.then((photoDocQuerySnapshot) => {
const firstPhotoDoc = photoDocQuerySnapshot.docs[0];
return firstPhotoDoc.get("photoURL");
});
//--------------------assemble this result---------------------
return Promises.all([userPreferencePromise, userPhotoPromise])
.then(([authorPreference, authorPhoto]) => {
return {
...tweetMappped,
author: authorPreference.username,
authorColor: authorPreference.color,
authorPhoto: authorPhoto.photoURL,
};
});
});
Promise.all(tweetsMappedPromises)
.then((tweetsMapped) => {
if (unsubscribed) return; // ignore result, dealing with out of date data
setTweets(tweetsMapped);
})
.catch((err) => {
if (unsubscribed) return; // ignore result, dealing with out of date data
// important! handle errors
});
});
return () => {
unsubscribed = true;
cancelSuscription();
}
}, []);
Notes:
You may benefit from using async/await syntax here instead.
On new onSnapshot calls, snapshot.docChanges() can be used to make it more efficient and speed up rerenders by only updating the entries that have changed (e.g. added/removed/modified). You would use setTweets(previousTweetsMapped => /* newTweetsMapped */) for this.
I have this function in WorkoutController.js
export async function getFavourites(FavRetrived) {
var FavList = []
var snapshot = await firebase
.firestore()
.collection("Favourites")
.doc(firebase.auth().currentUser.uid)
.collection("userFavourites")
.get()
snapshot.forEach((doc) => {
const favDoc = doc.data()
favDoc.id = doc.id
FavList.push(favDoc)
})
FavRetrived(FavList)
}
I used basically flatlists to get the datas from the collection and it works good but now I want to use the id's array to do some controls.
I think the second part of the code it creates an array of id but I don't know how to use it or show it.
in Screen.js I have
import { getFavourites } from '../context/WorkoutController'
const [FavList, setFavList] = useState()
useEffect(() => {
getDataFav()
}, [])
function getDataFav() {
getFavourites(FavRetrieved)
}
function FavRetrieved(FavList) {
setFavList(FavList)
}
Like this if I use a flatlist passing FavList as data I can see all the elements of the collection, but what if I want to show just the first id of the array?
I don't want to use where function, I need to see the datas as an array, for example something like FavList[0].name (but this doesn't work)
First, we need to tweak getFavourites so that it handles the case where the user isn't logged in with a meaningful error and it shouldn't use callbacks if you are making use of async/await syntax - just use Promise chaining instead.
export async function getFavourites() {
const user = firebase.auth().currentUser;
if (!user)
return Promise.reject(new Error("User must be signed in first"));
const favList = []
const snapshot = await firebase
.firestore()
.collection("Favourites")
.doc(user.uid)
.collection("userFavourites")
.get()
snapshot.forEach((doc) => {
const favDocData = doc.data()
favDocData.id = doc.id
favList.push(favDocData)
})
return favList
}
You would then use it in your component like so:
import { getFavourites } from '../context/WorkoutController'
// status of favList
const [status, setStatus] = useState("loading")
// array of favourites
const [favList, setFavList] = useState()
// error message to show user
const [errorMsg, setErrorMsg] = useState("")
useEffect(() => {
let disposed = false
getFavourites()
.then((newFavList) => {
if (disposed) return // component discarded, do nothing.
setFavList(newFavList)
setErrorMsg("")
setStatus("fetched")
})
.catch((err) => {
if (disposed) return // component discarded, do nothing.
console.error("getFavourites failed: ", err)
setErrorMsg("Failed to get favourites")
setStatus("error")
});
// return cleanup function
return () => disposed = true
}, []);
if (status === "loading")
return (<Spinner />)
if (status === "error")
return (<div key="error">{errorMsg}</div>)
// if here, favList is now an array of favourite documents data
return ( /* ... render favList ... */ )
export async function getFavourites(FavRetrived) {
var FavList = []
var snapshot = await firebase
.firestore()
.collection("Favourites")
.doc(firebase.auth().currentUser.uid)
.collection("userFavourites")
.get()
snapshot.forEach((doc) => {
const favDoc = doc.data();
const id = doc.id;
FavList.push({ id, ...favDoc })
})
FavRetrived(FavList)
}
You can access it by FavList[0].id
I'm getting data from Firebase and want to update state:
const [allProfile, setAllProfile] = useState([]);
.....
const displayProfileList = async () => {
try {
await profile
.get()
.then(querySnapshot => {
querySnapshot.docs.map(doc => {
const documentId = doc.id;
const nProfile = { id: documentId, doc: doc.data()}
console.log(nProfile);//nProfile contains data
setAllProfile([...allProfile, nProfile]);
console.log(allProfile); // is empty
}
);
})
} catch (error) {
console.log('xxx', error);
}
}
The setAllProfile will update the state when the iteration is done. So in order for your code to work, you will need to pass the callback function to the setAllProfile as shown in the docs
setAllProfile((prevState) => [...prevState, nProfile])
UPDATE
Example demonstrating this at work
Since setAllProfile is the asynchronous method, you can't get the updated value immediately after setAllProfile. You should get it inside useEffect with adding a allProfile dependency.
setAllProfile([...allProfile, nProfile]);
console.log(allProfile); // Old `allProfile` value will be printed, which is the initial empty array.
useEffect(() => {
console.log(allProfile);
}, [allProfile]);
UPDATE
const [allProfile, setAllProfile] = useState([]);
.....
const displayProfileList = async () => {
try {
await profile
.get()
.then(querySnapshot => {
const profiles = [];
querySnapshot.docs.map(doc => {
const documentId = doc.id;
const nProfile = { id: documentId, doc: doc.data()}
console.log(nProfile);//nProfile contains data
profiles.push(nProfile);
}
);
setAllProfile([...allProfile, ...profiles]);
})
} catch (error) {
console.log('xxx', error);
}
}
You are calling setState inside a map and therefore create few async calls, all referred to by current ..allProfile value call (and not prev => [...prev...)
Try
let arr=[]
querySnapshot.docs.map(doc => {
arr.push({ id: doc.id, doc: doc.data() })
}
setAllProfile(prev=>[...prev, ...arr])
I don't sure how the architecture of fetching the posts implemented (in terms of pagination and so on, so you might don't need to destruct ...prev
I am trying to grab data from firebase and it console logs correctly but array says length is 0
useEffect(() => {
let items = [];
const unsubscribe = store
.collection('users')
.doc(user.uid)
.collection('redirects')
.onSnapshot(snapShot => {
snapShot.forEach(getPath => {
const { path } = getPath.data();
store.doc(path).onSnapshot(doc => {
const data = doc.data();
items.push({ ...data });
});
});
});
setDocs(items);
setIsLoading(false);
return () => unsubscribe();
}, []);
console.log(docs);
Try something like this:
Your setState call should be inside the onSnapShot(()=>{}) callback, because the it's asynchronous. The way you're doing, you're basically trying to call setDocs() with an empty items array.
useEffect(() => {
let items = [];
const unsubscribe = store
.collection('users')
.doc(user.uid)
.collection('redirects')
.onSnapshot(snapShot => {
snapShot.forEach(getPath => {
const { path } = getPath.data();
store.doc(path).onSnapshot(doc => {
const data = doc.data();
items.push({ ...data });
});
});
setDocs(items);
setIsLoading(false);
});
//setDocs(items);
//setIsLoading(false);
return () => unsubscribe();
}, []);
As others have mentioned, it seems to be a async issue.
The console in chrome will show resolved object values, not necessarily what they were at run time.
To show you what i mean, change your console log from console.log(docs) to console.log(JSON.stringify(docs)) and it will show you the string value of docs at run time which should be an empty array, which would make the length 0 make sense (because it is 0 until the async call is resolved).