Why can't I delete data with Vuejs - firebase

Although it says status:ok in the console, the data in the firebase data is not deleted, where am I doing wrong?
`
deleteUser(userKey){
this.$resource("users" + userKey + ".json").delete()
.then(response => {
console.log(response)
})
}
`

Related

Why is firebase cloud function invoked in react-native not logging output?

I have a firebase cloud function:
exports.copyImage = functions.region('us-central1').https.onCall(async (data, context) => {
const { auth } = context || {}
const { uid } = auth || {}
if (!uid) throw 'Unauthenticated'
const srcBucketName = <bucket-name>'
const destinationBucketName = '<bucket-name'
const { imageFile, archiveId, sessionId } = data
const srcFileName = `message-attachments/${imageFile}`
const destinationFileName = `archived-attachments/${uid}/${imageFile}`
console.log(`source path: ${srcFileName}\ndestination path: ${destinationFileName}`)
const storage = new Storage()
storage
.bucket(srcBucketName)
.file(srcFileName)
.copy(storage.bucket(destinationBucketName).file(destinationFileName))
.then(() => {
console.log(`COPY SUCCESS: gs://${destinationBucketName}/${destinationFileName}`)
})
.catch(err => console.error('COPY ERROR: ' + err))
})
and I have a react-native project (v61.5) using react-native-firebase (v5) which calls this function:
firebase.functions().httpsCallable('copyFile')({
imageFile: fileName,
archiveId: uid,
sessionId
})
.then(() => {
// copied file
const ref = firebase.storage()
.ref('archived-attachments')
.child(uid)
.child(fileName)
ref.getDownloadURL()
.then(url => {
// do more
})
.catch(err => alert(err.message))
})
.catch(err => {
// copy error
})
the problem is im not getting any log output in the functions console when executing this function. the functions been successfully deployed as well. Any advice?
Updating my comment in this answer as it solves the issue.
The issue occurred because Jim has been triggering a different function copyFile
instead of copyImage.
mismatch between the function name exports.copyImage vs httpsCallable('copyFile').
Updating the function name solved the issue!

Accessing vuex actions inside a promise

I'm struggling to understand this conceptually.
So I'm trying to use a Vuex store action from within a second .then() function of a promise ( this.$store.dispatch('setAdditionalUserInfo', doc.data())) , and I'm getting the error of TypeError: Cannot read property '$store' of undefined.
Why can't I access this in the .then() function?
socialLogin () {
const provider = new firebase.auth.GoogleAuthProvider()
firebase.auth().signInWithPopup(provider)
.then(cred => {
const protoslug = cred.user.displayName + ' ' + cred.user.uid
this.slug = slugify(protoslug, {
replacement: '-',
remove: /[$*_+~.()'"!\-:#']/g,
lower: true
})
db.collection('users').doc(this.slug).set({
alias: this.slug,
role: 'customer',
// eslint-disable-next-line #typescript-eslint/camelcase
user_id: cred.user.uid
})
// set the user in the vuex store
this.$store.dispatch('setUser', cred.user)
return cred.user
})
.then((cred) => {
db.collection('users').where('user_id', '==', cred.uid)
.get()
.then(function (querySnapshot) {
querySnapshot.forEach(function (doc) {
console.log(doc.data())
this.$store.dispatch('setAdditionalUserInfo', doc.data())
})
})
.catch(function (error) {
console.log('Error getting documents: ', error)
})
})
}
I can see that the data is returned as it is logged out in the console. The project is in typescript, so its preventing me from trying self = this.
To propagate the value of this all the way down, you need to always use arrow functions. Change these lines:
.then(function (querySnapshot) {
querySnapshot.forEach(function (doc) {
console.log(doc.data())
this.$store.dispatch('setAdditionalUserInfo', doc.data())
})
})
.catch(function (error) {
console.log('Error getting documents: ', error)
})
to use arrow functions:
.then((querySnapshot) => {
querySnapshot.forEach((doc) => {
console.log(doc.data())
this.$store.dispatch('setAdditionalUserInfo', doc.data())
})
})
.catch((error) => {
console.log('Error getting documents: ', error)
})

Having trouble updating a document in Vue JS using Firebase's Firestore

I'm building a simple single page web app using Vue JS (Vue Cli 3) with Firebase's Firestore as the back-end database. I've managed to add, and delete records with ease. I'm running into an issue when trying to 'update' a user's details.
My code for this function is as follows:
saveEditUser() {
db.collection('users')
.where('email', '==', this.form.email)
.get()
.then(snap => {
snap.forEach(doc => {
doc.ref.update({
email: this.form.email
})
})
})
.then(() => {
console.log('Successfully updated the record')
})
.catch(error => {
console.error('There was an error editing the record: ' + error)
})
}
Some things that I've discovered during my attempts at debugging this:
This is not a scope issue where 'this' in the this.form.email is not available inside the forEach loop.
I thought this could be the case and so I declared a 'const vm = this' before the loop and tried to use vm.form.email, but no dice.
Also, when I try to update the email field to a simple string like 'abc' instead of a dynamic value such as this.form.email, it works!
After several spent hours on this ridiculous problem, I am officially stumped folks. Please send help!
Thank you.
TL;DR: the OP was updating a record with the same value, hence nothing appeared to change in the Firestore DB. However, in his code, there was the need to return the promise returned by the single asynchronous operation (or by the set of asynchronous operations)
Since your are potentially going to execute several asynchronous operations to the database in parallel (using the update() method, which return a promise, see doc) , you need to use Promise.all(), as follows.
saveEditUser() {
const email = this.form.email;
const= promises = [];
db.collection('users')
.where('email', '==', email )
.get()
.then(snap => {
snap.forEach(doc => {
promises.push(
doc.ref.update({
email: email //Actually the problems comes from here, see below
})
);
return Promise.all(promises);
})
})
.then(() => {
console.log('Successfully updated the record')
})
.catch(error => {
console.error('There was an error editing the record: ' + error)
})
}
If you are 100% sure your query will return only one doc you could update the doc directly, but then you have to return the promise returned by update(), as follows:
saveEditUser() {
const email = this.form.email;
db.collection('users')
.where('email', '==', email)
.get()
.then(snap => {
return snap.docs[0].ref.update({
email: email
});
})
.then(() => {
console.log('Successfully updated the record')
})
.catch(error => {
console.error('There was an error editing the record: ' + error)
})
}
Note: by declaring the email const at the beginning of the function, you should not encounter any problem of context anymore.
Update following our comments and discussion:
Actually you are updating with the SAME value of email. So it is normal you don't see any result. Just try to update with another value, like in the following code:
saveEditUser() {
const email = this.form.email;
db.collection('users')
.where('email', '==', email)
.get()
.then(snap => {
return snap.docs[0].ref.update({
email: 'john.doe#gmail.com'
});
})
.then(() => {
console.log('Successfully updated the record')
})
.catch(error => {
console.error('There was an error editing the record: ' + error)
})
}
If you want to test with a value from your form, just use two fields: one with the value to query and one with the new value, like:
<input v-model="form.mail" placeholder="mail to search for">
<input v-model="form.newMail" placeholder="new email">
.....
saveEditUser() {
const emailToQuery = this.form.email;
const newEmail = this.form.newMail;
db.collection('users')
.where('email', '==', emailToQuery )
.get()
.then(snap => {
return snap.docs[0].ref.update({
email: newEmail
});
})
.then(() => {
console.log('Successfully updated the record')
})
.catch(error => {
console.error('There was an error editing the record: ' + error)
})
}

retrieving an image from firebase storage to a vue app

I am trying to download an image from my firebase storage to render it in my Vue app, the upload from the application to the firebase storage is successful, however upon retrieval it gives me an error cannot read property '0' of undefined, i am using the firebase SDK in a Vue CLI 3 setup and vuex to manage my state. Here is the function setting in my actions in the main store.js file
let imageUrl
let key
firebase.database().ref('meetups').push(meetup)
.then((data) => {
key = data.key
return key
})
.then(key => {
const filename = payload.image.name
const ext = filename.slice(filename.lastIndexOf('.'))
return firebase.storage().ref('meetups/' + key + '.' + ext).put(payload.image)
})
.then(fileData => {
imageUrl = fileData.metadata.downloadURLs[0]
return firebase.database().ref('meetups').child(key).update({imageUrl: imageUrl})
})
.then(() => {
commit('createMeetup', {
...meetup,
imageUrl: imageUrl,
id: key
})
})
.catch((error) => {
console.log(error)
})
So it would seem you are doing Max's course on Vue. Excellent course but there are some slight changes to firebase since it was published. You can try this as I think the problem is you are not retrieving the image URL from storage so it isn't being inserted into your database so the app can't call it. It's trying to call "0". So change your createMeetup function to something like this:
createMeetup ({commit, getters}, payload) {
const meetup = {
title: payload.title,
location: payload.location,
description: payload.description,
preview: payload.preview,
date: payload.date,
creatorId: getters.user.id
}
let storageRef
let uploadTask
let key
firebase.database().ref('meetups').push(meetup)
.then((data) => {
key = data.key
return key
})
.then(key => {
const filename = payload.image.name
const ext = filename.slice(filename.lastIndexOf('.'))
storageRef = firebase.storage().ref();
uploadTask = storageRef.child('meetups/' + key + ext).put(payload.image)
return uploadTask
})
.then((uploadTask) => {
// Upload completed successfully, now we can get the download URL
uploadTask.ref.getDownloadURL().then((downloadURL) => {
firebase.database().ref('meetups').child(key).update({imageUrl: downloadURL})
.then(() => {
commit('createMeetup', {
...meetup,
imageUrl: downloadURL,
id: key
})
})
.catch((error) => {
})
})
})
},
And I think that should solve the problem.

Problem with dispatch() and if-else statement after adding another method

I have this action to fetch the details of a specific location url stored in Firebase.
The original code (Version 1) worked no problem, whereby I dispatch authGetToken(), the code recognises the token (string) stored in redux, then uses it to to fetch the stored data.
Version 1
return dispatch => {
dispatch(authGetToken())
.then(token => {
return fetch("https://myProject/location.json?auth=" + token);
})
.catch(() => {
alert("No valid token found!");
})
.then(res => {
if (res.ok) {
return res.json();
} else {
throw(new Error());
}
})
};
But now that I modified the url requirements to include the user UID as part of the url, it does not work. I know there must be a flaw in my logic but I can't see it.
What I was hoping to write is that once I dispatch authGetToken(), the token dispatches authGetUserUID then uses both strings (userUID and token) to fetch the data.
Version 2
return dispatch => {
dispatch(authGetToken())
.then(token => {
dispatch(authGetuserUID())
return fetch("https://myProject/location/"+ userUID + ".json?auth=" + token);
})
.catch(() => {
alert("No valid token found!");
})
.then(res => {
if (res.ok) {
return res.json();
} else {
throw(new Error());
}
})
};
Would appreciate you guys pointing out the obvious to me >< as I my noob eyes can't see it. Thanks in advance.
I think it might have something to do with userUID, it doesn't seem to be initialised anywhere. Maybe try something like this:
return dispatch => {
dispatch(authGetToken()).then(token => {
dispatch(authGetuserUID()).then(userUID=>{
return fetch("https://myProject/location/"+ userUID + ".json?auth=" + token);
})
})
.catch(() => {
alert("No valid token found!");
})
.then(res => {
if (res.ok) {
return res.json();
} else {
throw(new Error());
}
})
};

Resources