Pass variable to created hook Vue.js for Firestore reference - javascript

My goal is to:
Load one document and get the value for "account"
Then load a new document with "account" as one of the document names in firestore. I am using this.account for the path
<script>
// eslint-disable-next-line
import firestore from "firestore";
// eslint-disable-next-line
import NewEmployee from "#/components/updatePopups/NewEmployee";
import db from "#/components/fbInit";
import firebase from "firebase";
export default {
// eslint-disable-next-line
components: { NewEmployee },
data() {
return {
account: "",
users: [],
acc:[],
};
},
computed: {
computed() {
const user = firebase.auth().currentUser;
const info = [];
db
.collection("userProfiles")
.doc(user.uid)
.get()
.then(doc => {
const doc1content = doc.data();
return doc1content.account;
console.log(doc1content.account)
});
}
},
created() {
const user = firebase.auth().currentUser;
let account = computed();
let empRef = db.collection('userProfiles').doc(this.account).collection('employees');
let empCollection = empRef.get()
.then(snapshot => {
this.users = [];
snapshot.forEach(doc => {
console.log(doc.id, '=>', doc.data());
const data = {
id: doc.id,
Name: doc.data().Name,
GroupHex: doc.data().GroupHex,
DeviceType: doc.data().DeviceType,
UserIDInt: doc.data().UserIDInt,
SuperID: doc.data().SuperID,
misc: doc.data().misc,
Status: doc.data().Status,
};
this.users.push(data)
});
})
},
};
</script>
I keep getting undefined errors or value can't be "" or """
account is undefined
ReferenceError: computed is not defined
The reason I am not doing this all in one created hook is because I would like to use the snapshot feature to reload the page when there is a change automatically and I had trouble doing that when it was nested inside another doc.get(). I would like to have the "account" variable loaded and stored when the page is loaded(or before).
Any help would be greatly appreciated.

Related

want to add data in todo array how can i do this in firebase v9

I created a collection "user", nd then created doc as a current logged in user ui (you can see in screenshot). Now I want to add todo in that todo[] array. How can i do this using latest version of firebase v9?
I tried, but getting some error. Please check AddTodo() method below.
async register() {
createUserWithEmailAndPassword(auth, this.email, this.password)
.then((userCredential) => {
const currentUserUid = userCredential.user.uid;
return setDoc(doc(db, "users", currentUserUid), {
// add any additional user data here
name: "fullName",
email: "email",
todo: [],
});
})
.then(() => {
// User registration and document creation successful
})
.catch((error) => {
console.log(error.message);
});
},
async addTodo(){
if (this.newTodo != "" && this.newTask != "") {
const currentUser = auth.currentUser;
const currentUserUid = currentUser.uid;
await addDoc(collection(db, currentUserUid), [
{
title: this.newTodo,
task: this.newTask,
},
]);
}
}
Your second code snippet tries to add a new document to a collection named after the user's UID. That does not match the screenshot you have, which shows a document named after the UID in a collection names users.
To update the latter document, adding a task to the tasks array field:
async addTodo(){
if (this.newTodo != "" && this.newTask != "") {
const currentUser = auth.currentUser;
const currentUserUid = currentUser.uid;
await updateDoc(doc(db, 'users', currentUserUid), {
tasks: arrayUnion([
title: this.newTodo,
task: this.newTask,
]},
]);
}
}
Also see the Firebase documentation on adding and removing elements on an array field.

How to extract data when onSnapshot is returned in realtime firestore?

I have two files contact.js and functions.js. I am using firestore realtime functionality.
Here is my functions.js file code:
export const getUserContacts = () => {
const contactDetailsArr = [];
return db.collection("users").doc(userId)
.onSnapshot(docs => {
const contactsObject = docs.data().contacts;
for (let contact in contactsObject) {
db.collection("users").doc(contact).get()
.then(userDetail => {
contactDetailsArr.push({
userId: contact,
lastMessage: contactsObject[contact].lastMsg,
time: contactsObject[contact].lastMsgTime,
userName:userDetail.data().userName,
email: userDetail.data().emailId,
active: userDetail.data().active,
img: userDetail.data().imageUrl,
unreadMsg:contactsObject[contact].unreadMsg
})
})
}
console.log(contactDetailsArr);
return contactDetailsArr;
})
}
in contact.js when I do:
useEffect(() => {
let temp = getUserContacts();
console.log(temp);
}, [])
I want to extract data of contactDetailsArr in contacts.js but I get the value of temp consoled as:
ƒ () {
i.Zl(), r.cs.ws(function () {
return Pr(r.q_, o);
});
}
How do I extract the array data in my case?
The onSnapshot() returns a function that can be used to detach the Firestore listener. When using a listener, it's best to set the data directly into state rather than returning something from that function. Try refactoring the code as shown below:
const [contacts, setContacts] = useState([]);
useEffect(() => {
const getUserContacts = () => {
const contactDetailsArr = [];
const detach = db.collection("users").doc(userId)
.onSnapshot(docs => {
const contactsObject = docs.data().contacts;
const contactsSnap = await Promise.all(contactsObject.map((c) => db.collection("users").doc(c).get()))
const contactDetails = contactsSnap.map((d) => ({
id: d.id,
...d.data()
// other fields like unreadMsg, time
}))
// Update in state
setContacts(contactDetails);
})
}
getUserContacts();
}, [])
Then use contacts array to map data in to UI directly.
Assumptions
This answer assumes a user's data looks like this in your Firestore:
// Document at /users/someUserId
{
"active": true,
"contacts": {
"someOtherUserId": {
"lastMsg": "This is a message",
"lastMsgTime": /* Timestamp */,
"unreadMsg": true // unclear if this is a boolean or a count of messages
},
"anotherUserId": {
"lastMsg": "Hi some user! How are you?",
"lastMsgTime": /* Timestamp */,
"unreadMsg": false
}
},
"emailId": "someuser#example.com",
"imageUrl": "https://firebasestorage.googleapis.com/b/bucket/o/images%20stars.jpg",
"userName": "Some User"
}
Note: When asking questions in the future, please add examples of your data structure similar to the above
Attaching Listeners with Current Structure
The structure as shown above has a number of flaws. The "contacts" object in the user's data should be moved to a sub-collection of the user's main document. The reasons for this include:
Any user can read another user's (latest) messages (which can't be blocked with security rules)
Any user can read another user's contacts list (which can't be blocked with security rules)
As an individual user messages more users, their user data will grow rapidly in size
Each time you want to read a user's data, you have to download their entire message map even if not using it
As you fill out a user's contacts array, you are fetching their entire user data document even though you only need their active, email, imageUrl, and userName properties
Higher chance of encountering document write conflicts when two users are editing the contact list of the same user (such as when sending a message)
Hard to (efficiently) detect changes to a user's contact list (e.g. new addition, deletion)
Hard to (efficiently) listen to changes to another user's active status, email, profile image and display name as the listeners would be fired for every message update they receive
To fetch a user's contacts once in your functions.js library, you would use:
// Utility function: Used to hydrate an entry in a user's "contacts" map
const getContactFromContactMapEntry = (db, [contactId, msgInfo]) => {
return db.collection("users")
.doc(contactId)
.get()
.then((contactDocSnapshot) => {
const { lastMsg, lastMsgTime, unreadMsg, userName } = msgInfo;
const baseContactData = {
lastMessage: lastMsg,
time: lastMsgTime,
unreadMsg,
userId: contactId
}
if (!contactDocSnapshot.exists) {
// TODO: Decide how to handle unknown/deleted users
return {
...baseContactData,
active: false, // deleted users are inactive, nor do they
email: null, // have an email, image or display name
img: null,
userName: "Deleted user"
};
}
const { active, emailId, imageUrl, userName } = contactDocSnapshot.data();
return {
...baseContactData,
active,
email: emailId,
img: imageUrl,
userName
};
});
};
export const getUserContacts = (db, userId) => { // <-- note that db and userId are passed in
return db.collection("users")
.doc(userId)
.get()
.then((userDataSnapshot) => {
const contactsMetadataMap = userDataSnapshot.get("contacts");
return Promise.all( // <-- waits for each Promise to complete
Object.entries(contactsMetadataMap) // <-- used to get an array of id-value pairs that we can iterate over
.map(getContactFromContactMapEntry.bind(null, db)); // for each contact, call the function (reusing db), returning a Promise with the data
);
});
}
Example Usage:
getUserContacts(db, userId)
.then((contacts) => console.log("Contacts data:", contacts))
.catch((err) => console.error("Failed to get contacts:", err))
// OR
try {
const contacts = await getUserContacts(db, userId);
console.log("Contacts data:", contacts);
} catch (err) {
console.error("Failed to get contacts:", err)
}
To fetch a user's contacts, and keep the list updated, using a function in your functions.js library, you would use:
// reuse getContactFromContactMapEntry as above
export const useUserContacts = (db, userId) => {
if (!db) throw new TypeError("Parameter 'db' is required");
const [userContactsData, setUserContactsData] = useState({ loading: true, contacts: [], error: null });
useEffect(() => {
// no user signed in?
if (!userId) {
setUserContactsData({ loading: false, contacts: [], error: "No user signed in" });
return;
}
// update loading status (as needed)
if (!userContactsData.loading) {
setUserContactsData({ loading: true, contacts: [], error: null });
}
let detached = false;
const detachListener = db.collection("users")
.doc(userId)
.onSnapshot({
next: (userDataSnapshot) => {
const contactsMetadataMap = userDataSnapshot.get("contacts");
const hydrateContactsPromise = Promise.all( // <-- waits for each Promise to complete
Object.entries(contactsMetadataMap) // <-- used to get an array of id-value pairs that we can iterate over
.map(getContactFromContactMapEntry.bind(null, db)); // for each contact, call the function (reusing db), returning a Promise with the data
);
hydrateContactsPromise
.then((contacts) => {
if (detached) return; // detached already, do nothing.
setUserContactsData({ loading: false, contacts, error: null });
})
.catch((err) => {
if (detached) return; // detached already, do nothing.
setUserContactsData({ loading: false, contacts: [], error: err });
});
},
error: (err) => {
setUserContactsData({ loading: false, contacts: [], error: err });
}
});
return () => {
detached = true;
detachListener();
}
}, [db, userId])
}
Note: The above code will not (due to complexity):
react to changes in another user's active status, email or profile image
properly handle when the setUserContactsData method is called out of order due to network issues
handle when db instance is changed on every render
Example Usage:
const { loading, contacts, error } = useUserContacts(db, userId);
Attaching Listeners with Sub-collection Structure
To restructure your data for efficiency, your structure would be updated to the following:
// Document at /users/someUserId
{
"active": true,
"emailId": "someuser#example.com",
"imageUrl": "https://firebasestorage.googleapis.com/b/bucket/o/images%20stars.jpg",
"userName": "Some User"
}
// Document at /users/someUserId/contacts/someOtherUserId
{
"lastMsg": "This is a message",
"lastMsgTime": /* Timestamp */,
"unreadMsg": true // unclear if this is a boolean or a count of messages
}
// Document at /users/someUserId/contacts/anotherUserId
{
"lastMsg": "Hi some user! How are you?",
"lastMsgTime": /* Timestamp */,
"unreadMsg": false
}
Using the above structure provides the following benefits:
Significantly better network performance when hydrating the contacts list
Security rules can be used to ensure users can't read each others contacts lists
Security rules can be used to ensure a message stays private between the two users
Listening to another user's profile updates can be done without reading or being notified of any changes to their other private messages
You can partially fetch a user's message inbox rather than the whole list
The contacts list is easy to update as two users updating the same contact entry is unlikely
Easy to detect when a user's contact entry has been added, deleted or modified (such as receiving a new message or marking a message read)
To fetch a user's contacts once in your functions.js library, you would use:
// Utility function: Merges the data from an entry in a user's "contacts" collection with that user's data
const mergeContactEntrySnapshotWithUserSnapshot = (contactEntryDocSnapshot, contactDocSnapshot) => {
const { lastMsg, lastMsgTime, unreadMsg } = contactEntryDocSnapshot.data();
const baseContactData = {
lastMessage: lastMsg,
time: lastMsgTime,
unreadMsg,
userId: contactEntryDocSnapshot.id
}
if (!contactDocSnapshot.exists) {
// TODO: Handle unknown/deleted users
return {
...baseContactData,
active: false, // deleted users are inactive, nor do they
email: null, // have an email, image or display name
img: null,
userName: "Deleted user"
};
}
const { active, emailId, imageUrl, userName } = contactDocSnapshot.data();
return {
...baseContactData,
active,
email: emailId,
img: imageUrl,
userName
};
}
// Utility function: Used to hydrate an entry in a user's "contacts" collection
const getContactFromContactsEntrySnapshot = (db, contactEntryDocSnapshot) => {
return db.collection("users")
.doc(contactEntry.userId)
.get()
.then((contactDocSnapshot) => mergeContactEntrySnapshotWithUserSnapshot(contactEntryDocSnapshot, contactDocSnapshot));
};
export const getUserContacts = (db, userId) => { // <-- note that db and userId are passed in
return db.collection("users")
.doc(userId)
.collection("contacts")
.get()
.then((userContactsQuerySnapshot) => {
return Promise.all( // <-- waits for each Promise to complete
userContactsQuerySnapshot.docs // <-- used to get an array of entry snapshots that we can iterate over
.map(getContactFromContactsEntrySnapshot.bind(null, db)); // for each contact, call the function (reusing db), returning a Promise with the data
);
});
}
Example Usage:
getUserContacts(db, userId)
.then((contacts) => console.log("Contacts data:", contacts))
.catch((err) => console.error("Failed to get contacts:", err))
// OR
try {
const contacts = await getUserContacts(db, userId);
console.log("Contacts data:", contacts);
} catch (err) {
console.error("Failed to get contacts:", err)
}
To fetch a user's contacts in a way where it's kept up to date, we first need to introduce a couple of utility useEffect wrappers (there are libraries for more robust implementations):
export const useFirestoreDocument = ({ db, path }) => {
if (!db) throw new TypeError("Property 'db' is required");
const [documentInfo, setDocumentInfo] = useState({ loading: true, snapshot: null, error: null });
useEffect(() => {
if (!path) {
setDocumentInfo({ loading: false, snapshot: null, error: "Invalid path" });
return;
}
// update loading status (as needed)
if (!documentInfo.loading) {
setDocumentInfo({ loading: true, snapshot: null, error: null });
}
return db.doc(path)
.onSnapshot({
next: (docSnapshot) => {
setDocumentInfo({ loading: false, snapshot, error: null });
},
error: (err) => {
setDocumentInfo({ loading: false, snapshot: null, error: err });
}
});
}, [db, path]);
return documentInfo;
}
export const useFirestoreCollection = ({ db, path }) => {
if (!db) throw new TypeError("Property 'db' is required");
const [collectionInfo, setCollectionInfo] = useState({ loading: true, docs: null, error: null });
useEffect(() => {
if (!path) {
setCollectionInfo({ loading: false, docs: null, error: "Invalid path" });
return;
}
// update loading status (as needed)
if (!collectionInfo.loading) {
setCollectionInfo({ loading: true, docs: null, error: null });
}
return db.collection(path)
.onSnapshot({
next: (querySnapshot) => {
setCollectionInfo({ loading: false, docs: querySnapshot.docs, error: null });
},
error: (err) => {
setCollectionInfo({ loading: false, docs: null, error: err });
}
});
}, [db, path]);
return collectionInfo;
}
To use that method to hydrate a contact, you would call it from a ContactEntry component:
// mergeContactEntrySnapshotWithUserSnapshot is the same as above
const ContactEntry = ({ db, userId, key: contactId }) => {
if (!db) throw new TypeError("Property 'db' is required");
if (!userId) throw new TypeError("Property 'userId' is required");
if (!contactId) throw new TypeError("Property 'key' (the contact's user ID) is required");
const contactEntryInfo = useFirestoreDocument(db, `/users/${userId}/contacts/${contactId}`);
const contactUserInfo = useFirestoreDocument(db, `/users/${contactId}`);
if ((contactEntryInfo.loading && !contactEntryInfo.error) && (contactUserInfo.loading && !contactUserInfo.error)) {
return (<div>Loading...</div>);
}
const error = contactEntryInfo.error || contactUserInfo.error;
if (error) {
return (<div>Contact unavailable: {error.message}</div>);
}
const contact = mergeContactEntrySnapshotWithUserSnapshot(contactEntryInfo.snapshot, contactUserInfo.snapshot);
return (<!-- contact content here -->);
}
Those ContactEntry components would be populated from a Contacts component:
const Contacts = ({db}) => {
if (!db) throw new TypeError("Property 'db' is required");
const { user } = useFirebaseAuth();
const contactsCollectionInfo = useFirestoreCollection(db, user ? `/users/${user.uid}/contacts` : null);
if (!user) {
return (<div>Not signed in!</div>);
}
if (contactsCollectionInfo.loading) {
return (<div>Loading contacts...</div>);
}
if (contactsCollectionInfo.error) {
return (<div>Contacts list unavailable: {contactsCollectionInfo.error.message}</div>);
}
const contactEntrySnapshots = contactsCollectionInfo.docs;
return (
<>{
contactEntrySnapshots.map(snapshot => {
return (<ContactEntry {...{ db, key: snapshot.id, userId: user.uid }} />);
})
}</>
);
}
Example Usage:
const db = firebase.firestore();
return (<Contacts db={db} />);
Your code seems to be not written with async/await or promise like style
e.g. contactDetailsArr will be returned as empty array
also onSnapshot creates long term subscription to Firestore collection and could be replaced with simple get()
See example on firestore https://firebase.google.com/docs/firestore/query-data/get-data#web-version-9_1

How can my code await the firebase responce before returning the object

My code works, and the console.log is showing the object, and if i go to my firebase console and change the data then it is updated in realtime.
However when initially direcred by my router to the PlaylistDetails.vue it is taking the empty fields and displaying them whilst my program talks to firebase, when data is returned the console prints but my fields are still blank.
im assuming i need to get an async await function in there somewhere, or v:bind
export default {
props: ["id"],
setup(props) {
const db = getFirestore();
const docRef = doc(db, "playlists", props.id);
const playlist = { id: "", title: ""};
const unsub = onSnapshot(docRef, (doc) => {
playlist.id = doc.id;
playlist.title = doc.data().title;
console.log(playlist);
});
watchEffect((onInvalidate) => {
onInvalidate(() => unsub());
});
return { playlist };
},
};

Adding Comment to The Post using React, Redux and Firebase

When i try adding comment to the post i get this error:
FirebaseError: Function CollectionReference.doc() cannot be called with an empty path.
Here is my code:
Im using this to push to Firebase, postId is from Redux.
const postId = useSelector(selectPostId);
useEffect(() => {
// za komentiranje na slika
if (postId) {
db.collection("posts")
.doc(postId)
.collection("comments")
.orderBy("timestamp", "desc")
.onSnapshot((snapshot) => {
setComments(snapshot.docs.map((doc) => doc.data()));
});
}
}, [postId]);
const postComment = (e) => {
e.preventDefault();
db.collection("posts").doc(postId).collection("comments").add({
text: comment,
username: user.displayName,
timestamp: firebase.firestore.FieldValue.serverTimestamp(),
});
setComment("");
};
Here is the Redux :
export const postSlice = createSlice({
name: "post",
initialState: {
postId: null,
commentId: null,
},
reducers: {
setPost: (state, action) => {
state.postId = action.payload.postId;
},
setComments: (state, action) => {
state.commentId = action.payload.commentId;
},
},
});
export const { setPost, setComments } = postSlice.actions;
export const selectPostId = (state) => state.post.postId;
export const selectCommentId = (state) => state.post.commentId;
export default postSlice.reducer;
Looks like you are passing a wrong document id to posts collection:
verify that postId global state has a value.
if postId is a valid value then, check posts collection and see if you are passing the right id to the right collection " Database Architecture "
that is what the error is about.

Vue.js object properties are "hidden" after assignment

I can retrieve data from a Firebase database, but when I try to assign the fetched data from the database, the object properties require you to invoke a getter (I mean I can't access them after assignment)
This is the Vue instance.
Yes, I know. This is formatted weirdly, this is something that VS Code does for me...
export default {
name: "Home",
data() {
return {
users: []
};
},
created() {
db.collection("users")
.get()
.then(snapshot => {
snapshot.forEach(doc => {
let user = doc.data();
user.id = doc.id;
this.users.push(user);
console.log(this.users);
});
});
}
};
When I open up the console I need to click on three dots to get the actual data.
The following should do the trick:
export default {
name: "Home",
data() {
return {
users: []
};
},
created() {
db.collection("users")
.get()
.then(snapshot => {
let usersArray = [];
snapshot.forEach(doc => {
let user = doc.data();
user.id = doc.id;
usersArray.push(user);
});
this.users = usersArray;
console.log(this.users);
});
}
};

Categories

Resources