I am using Nuxt and it is recommended that we use async data for SSR.
I have this piece of code below:
async asyncData({ params }) {
console.log("params ...");
console.log(params.id);
let asyncDataDescription = "";
await firebase
.firestore()
.collection("posts")
.where("ytid", "==", params.id)
.get()
.then(querySnapshot => {
querySnapshot.forEach(doc => {
asyncDataDescription = doc.data().ytDescription;
});
console.log("description ...");
console.log(asyncDataDescription);
return { aSyncDescription: asyncDataDescription };
});
},
In the console log, I can see the data correctly returned from firestore but somehow when I try to display the data:
<div>{{ aSyncDescription }}</div>
It is not showing. Do I miss anything here? The page that talks about async data is here https://nuxtjs.org/api
Do you see this .then(querySnapshot => { ?
You are returning your result to an callback function. Rewrite it like this
async asyncData({ params }) {
console.log("params ...");
console.log(params.id);
let asyncDataDescription = "";
let querySnapshot = await firebase
.firestore()
.collection("posts")
.where("ytid", "==", params.id)
.get()
querySnapshot.forEach(doc => {
asyncDataDescription = doc.data().ytDescription;
});
console.log("description fdkjfdk");
console.log(asyncDataDescription);
return { aSyncDescription: asyncDataDescription };
},
Related
How do I properly call a function in a useEffect? Only want to call the function on page load.
I've got multiple functions that are being called in a use effect but the way it's set up I'm getting 1000+ reads and maxing out my quota instantly.
const [user, loading] = useAuthState(auth);
const [myDisplayName, setMyDisplayName] = useState("");
const [projectList, setProjectList] = useState([])
useEffect(()=>{
if(!user) navigate("/login")
fetchUserName();
fetchTotalProjects();
},[])
const fetchUserName = async () => {
try {
const query = await db
.collection("user")
.where("uid", "==", user?.uid)
.get();
const data = await query.docs[0].data();
setMyDisplayName(data.firstName);
} catch (err) {
console.error(err);
}
};
const fetchTotalProjects = async () => {
try {
const query = await db
.collection("projects")
.where("uid", "==", user?.uid)
.get()
.then((snapshot) => {
const tempData = [];
snapshot.forEach((doc) => {
const data = doc.data();
tempData.push(data);
});
setProjectList(tempData);
});
const data = await query.docs[0].data();
setProjectList(data);
} catch (err) {
console.error(err);
}
};
Fixed the issue. Getting the UID from Firebase was coming back undefined the first 3 -5 times and then it would get it, meaning the useEffect would fire until the data was retrieved.
Solution: Get your user uid from Firebase like this
const user = auth?.currentUser;
I want to pass data from /api/firestore/read.js to mainServer.js.
It does have the document, it prints, but does not return the data.
mainServer.js
app.get("/api/profile", async (req, res) => {
const uid = req.user.uid;
const userReader = new usersReader(uid);
const data = await userReader.readData();
console.log("Data", data); // data is undefined
res.status(200).send(data);
});
read.js
const admin = require("../../firebase-config").admin;
class ReadFireDb {
constructor(_uid) {
this.uid = _uid;
}
async readData() {
await admin
.firestore()
.collection("users")
.doc(this.uid)
.get()
.then((snapShot) => {
if (snapShot.exists) {
console.log(snapShot.data()); // here i print data correctly
return snapShot.data(); // here is the problem
} else {
return null;
}
})
.catch((err) => console.log(err));
}
}
module.exports = {
ReadFireDb,
};
how is the correct way to return this data?
This is the answer:`
Just make some changes to read.js
const admin = require("../../firebase-config").admin;
class ReadFireDb {
data;
constructor(_uid) {
this.uid = _uid;
}
async readData() {
await admin
.firestore()
.collection("users")
.doc(this.uid)
.get()
.then((snapShot) => {
if (snapShot.exists) this.data = snapShot.data();
})
.catch((err) => console.log(err));
return this.data;
}
}
module.exports = {
ReadFireDb,
};
I have my function on my class and i have to catch my subcollection. everything works fine with my collection (my console.log is working) but when i tried to catch something on my subcollection i have this error :
TypeError: undefined is not a function (near '...(0, _firestore.default)().collection("Teams").doc(docid).collection("membersList").where("statut", "==", "Validé").then...')
also my code :
GetMembersTeam = async () => {
firestore()
.collection("Teams")
.where("tokenTeam", "==", "c2z3f4vb3bh")
.get()
.then((querySnapshot) => {
if (querySnapshot.empty) {
console.log("no documents found");
} else {
querySnapshot.forEach((doc) => {
let Teams = doc._data;
let docid = doc.id;
firestore()
.collection("Teams")
.doc(docid)
.collection("membersList")
.where("statut", "==", "Validé")
.then(async (querySnapshot) => {
if (querySnapshot.empty) {
console.log("no documents found");
} else {
querySnapshot.forEach(async (doc) => {
let Teams = doc._data;
let docid = doc.id;
console.log(docid);
});
}
});
});
}
});
};
componentDidMount() {
this.GetViewTeam();
this.GetMembersTeam();
}
Are you missing a get()?
firestore()
.collection("Teams")
.doc(docid)
.collection("membersList")
.where("statut", "==", "Validé")
.get() //<- are you missing a get?
.then(async (querySnapshot) => {
if (querySnapshot.empty) {
console.log("no documents found");
} else {
querySnapshot.forEach(async (doc) => {
let Teams = doc._data;
let docid = doc.id;
console.log(docid);
});
}
native, i had tried using await and .then but when i run the code it will direct skip into dispatch(successGetPostList)
userRef = firestore.collection('user')
const postList = []
await Promise.all(user.userFollowing.map(async (val) => {
postRef = firestore.collection('post').where('postOwner', '==', firestore.collection('user').doc(val))
await postRef.onSnapshot(async (collection) => {
await Promise.all(collection._docs.map(async (doc) => {
let post =doc.data()
await post.postOwner.get().then((user)=>{
let owner={
...user.data()
}
post ={
...post,
postId:doc.id,
owner:owner
}
postList.push(post)
})
}))
})
}))
dispatch(_successGetPostList(postList))
Using Firestor on React Native.
I am getting this error:
Error: Query.get failed: First argument must be an object
When I try to fetch User data from other collection(Item), but that would not work.
export const itemsFetch = () => {
return (dispatch) => {
firebase.firestore().collection('items').get()
.then((snapshot) => {
const items = snapshot.docs.map(doc => doc.data());
return items
})
.then((items) => {
const userPromises = items.map((item, itemId) => {
const userId = item.userId;
console.log('userId: ', userId);
return firebase.firestore().collection('users').get(userId)
.then((snapshot) => {
console.log('snapshot:', snapshot);
const user = snapshot.docs.data();
return user;
console.log('user:', user);
})
.then(user => ({...item, user: user, itemId}));
});
dispatch({ type: 'ui/loading/hide' });
return Promise.all(userPromises);
})
};
};
I could get data snapshot but I cannot realize still.
get() doesn't take an argument like this:
return firebase.firestore().collection('users').get(userId)
If you want to fetch a document by ID, you need to build a DocumentReference using doc(), and call get() on it:
return firebase.firestore().collection('users').doc(userId).get()
That will return a promise the yields a single DocumentSnapshot with the contents of that document.
See QuerySnapshot documentation. The .where is optional.
let query = firestore.collection('col').where('foo', '==', 'bar');
query.get().then(querySnapshot => {
let docs = querySnapshot.docs;
for (let doc of docs) {
console.log(`Document found at path: ${doc.ref.path}`);
}
});