Issue
I have a problem trying to use a variable inside my async function in Vue
this is in methods:
methods: {
async editar(event) {
db.collection("products").doc(event).get().then((doc) => {
const productData = doc.data();
console.log("Nombre: ", productData.nombre); /* this */
console.log("Stock: ", productData.stock);
}).catch((error) => {
console.log("Error getting document:", error);
});
const alert = await alertController.create({
cssClass: 'alertClass',
header: 'Editar producto',
message: '¿QuĂ© deseas cambiar?',
inputs: [
{
name: 'nuevoNombre',
type: 'text',
placeholder: 'Nombre',
value: '' /* here */
},
{
name: 'nuevoStock',
type: 'number',
placeholder: 'Stock'
}
],
buttons: [
{
text: 'Cancelar',
role: 'cancel',
cssClass: 'secondary',
handler: () => {
console.log('Cancelado');
},
},
{
text: 'Aceptar',
handler: (data) => {
console.log('Se actualiza el doc: ' + event);
db.collection("products").doc(event).update({
nombre: data.nuevoNombre,
stock: data.nuevoStock
}).then(() => {
console.log("Nuevo nombre:", data.nuevoNombre);
console.log("Nuevo stock:", data.nuevoStock);
window.location.reload();
}).catch((error) => {
console.log("Error al intentar cambiar los valores", error);
});
},
},
],
});
return alert.present();
}
}
I want to use productData.nombre in the value inside the alertController. I was trying a lot of things but nothing works :(
I hope you can understand my question
Solution
const productData = doc.data();
const
defined productData
only can be reference at cloest scope.
At your situation, scope is
db.collection("products").doc(event).get().then((doc) => {
const productData = doc.data(); // only referenced in this scope (arrow function)
console.log("Nombre: ", productData.nombre); /* this */
console.log("Stock: ", productData.stock);
})
You can define variable before give it a value like this
async function editar(event) {
let productData;
db.collection("products")
.doc(event)
.get()
.then((doc) => {
productData = doc.data();
console.log("Nombre: ", productData.nombre); /* this */
console.log("Stock: ", productData.stock);
})
.catch((error) => {
console.log("Error getting document:", error);
});
const alert = await alertController.create({
// your code
})
}
Answered By - Ryan Leung
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.