Update state with Object using React Hooks - reactjs

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

Related

How to assign objects to an array

I am querying data from firebase, I then want to assign the fetch data to be an array
This is my code
let list = [];
dispatch(fetchUsersPending());
db.collection("users").get().then((querySnapshot) => {
querySnapshot.forEach((doc) => {
list.push({...doc.data()});
console.log('All Users: ', list);
dispatch(fetchUsersSuccess(list));
});
}).catch((error) => {
var errorMessage = error.message;
console.log('Error fetching data', errorMessage);
dispatch(fetchUsersFailed({ errorMessage }));
});;
But in my console am getting an error showing Error fetching data Cannot add property 1, object is not extensible in react firebase
I think your current approach also causes to many unnecessary dispatches to the store. With the following solution you only map your array to documents once and then dispatch them all at once.
With async/await
const fetchData = async () => {
try {
dispatch(fetchUsersPending());
const users = (await db.collection('users').get()).docs.map((doc) => ({ ...doc.data()}));
dispatch(fetchUsersSuccess(users));
} catch (errorMessage) {
dispatch(fetchUsersFailed({ errorMessage }));
}
}
With .then()
const fetchData = () => {
dispatch(fetchUsersPending());
const users = db.collection('users').get().then((snapshot) => {
const users = snapshot.docs.map((doc) => ({ ...doc.data() }));
dispatch(fetchUsersSuccess(users));
}).catch((errorMessage) {
dispatch(fetchUsersFailed({ errorMessage }));
});
}

React app backend firestore useEffect not working correctly

I am trying to keep track of the number of visitors my website gets using firestore as a backend.
I have two functions in my useEffect hook getVistorCount, and updateVistorCount. getVistorCount gets the doc containing the vistor_count variable from firestore and saves that array of data to state.
My updateVistorCount function gets the id and data of the document I am trying to update from state. The problem is that my state is initialized to an empty array so when I try to get the id and vistor_count from state I get the error "Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'id')" because the array from state is empty.
I am also getting the following warning in VSCode: "React Hook useEffect has missing dependencies: 'numberOfVistors' and 'portfolioStatesRef'. Either include them or remove the dependency array"
Here is the current code:
const portfolioStatesRef = collection(db, "portfolio-stats")
useEffect (() => {
let sessionKey = sessionStorage.getItem("sessionKey")
const getVistorCount = async () => {
const dataFromPortfolioStatsCollection = await getDocs(portfolioStatesRef)
setnumberOfVistors(dataFromPortfolioStatsCollection.docs.map((doc) => {
return ({ ...doc.data(), id: doc.id })
}))
}
const updateVistorCount = async () => {
const portfolioStatsDoc = doc(db, "portfolio-stats", numberOfVistors[0].id)
const updatedFields = {vistor_count: numberOfVistors[0].vistor_count + 1}
await updateDoc(portfolioStatsDoc, updatedFields)
}
getVistorCount()
if (sessionKey === null)
{
sessionStorage.setItem("sessionKey", "randomString")
updateVistorCount()
}
}, [])
Maybe using two effects can achieve what you want. First to get visitors:
useEffect (() => {
let sessionKey = sessionStorage.getItem("sessionKey")
const getVistorCount = async () => {
const dataFromPortfolioStatsCollection = await getDocs(portfolioStatesRef)
setnumberOfVistors(dataFromPortfolioStatsCollection.docs.map((doc) => {
return ({ ...doc.data(), id: doc.id })
}))
}
getVistorCount()
}, [])
Second to update count
useEffect (() => {
if(!numberOfVistors.length) return;
const updateVistorCount = async () => {
const portfolioStatsDoc = doc(db, "portfolio-stats", numberOfVistors[0].id)
const updatedFields = {vistor_count: numberOfVistors[0].vistor_count + 1}
await updateDoc(portfolioStatsDoc, updatedFields)
}
updateVistorCount()
}, [numberOfVistors])

Getting UNDEFINED values from Firestore onSnapshot + Promises for my React State

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.

What am I doing wrong to get an array from firebase

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 am getting data back but the array length is returned as 0

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).

Resources