How can I use this variable on Vue.js? - vue.js

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

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

db.collection("products") seems like an async function, using await before calling it, or you will miss db data since it's not ready.
You should declare variable outside your function which getting db data first, due to javascript scope
Here is a similar easy example on codepen

Related

Why updating object in array is not working in VUE?

I'm trying to make an update and I managed to do it in the firebase, but in the store is not updating. Here is my code
editCar() {
let result = this.balmUI.validate(this.formData);
let { valid, message } = result;
this.message = message;
console.log(`Vrei sa editezi masina: ${this.formData.vehicle}`);
console.log(utils.url);
if (valid) {
let data = {
vehicle: this.formData.vehicle,
color: this.formData.color,
fuel: this.formData.fuel,
status: this.formData.status,
price: this.formData.price,
};
let requestParameters = { ...utils.globalRequestParameters };
let token = window.localStorage.getItem("token");
requestParameters.headers.Authorization = "Bearer " + token;
requestParameters.method = "PUT";
requestParameters.body = JSON.stringify(data);
fetch(utils.url + "cars/" + this.formData.id, requestParameters)
.then((res) => res.json())
.then((res) => {
console.log(res.message);
if (
res.message === "Decoding error!" ||
res.message === "Your token expired!"
) {
console.log("nu ai voie!");
} else {
data.id = res.id;
this.$store.dispatch("editCar", data);
this.$router.push("/");
}
});
}
This is the index from store, which contais my mutation and action. Anything else is working properly
import { createStore } from 'vuex'
export default createStore({
state: {
cars: [],
isAuthentif: false
},
getters: {
cars: state => {
return state.cars
}
},
mutations: {
SET_AUTH: (state, status) => {
state.isAuthentif = status
},
SET_CARS: (state, cars) => {
state.cars = cars
},
ADD_CAR: (state, car) => {
state.cars.push(car)
},
DELETE_CAR: (state, id) => {
var index = state.cars.findIndex(car => car.id == id)
state.cars.splice(index, 1);
},
EDIT_CAR: (state, car) => {
state.cars.forEach(c => {
if(c.id === car.id) {
c = car;
}
})
}
},
actions: {
login: ({ commit }, payload) => {
commit('SET_AUTH', payload)
},
fetchCars: ({ commit }, payload) => {
commit('SET_CARS', payload)
},
addCar: ({ commit }, payload) => {
commit('ADD_CAR', payload)
},
deleteCar: ({ commit }, payload) => {
commit('DELETE_CAR', payload)
},
editCar: ({ commit }, payload) => {
commit('EDIT_CAR', payload)
}
},
modules: {
}
})
EDIT_CAR is the problem, I think.
What is wrong? Why it is not updating on the screen.
I've also tried to use this https://vuex.vuejs.org/guide/mutations.html#object-style-commit
like this c = {...c, car} but is not working
Your problem is not in the mutation. The problem is in your editCar() in here this.$store.dispatch("editCar", data);
You put data, and with vehicle, color, fuel, status and price and then in your mutation you verify ID. You didn't pass any id. You cand make a new object if you don't want you id, like this:
editCar() {
let result = this.balmUI.validate(this.formData);
let { valid, message } = result;
this.message = message;
console.log(`Vrei sa editezi masina: ${this.formData.vehicle}`);
console.log(utils.url);
if (valid) {
let data = {
vehicle: this.formData.vehicle,
color: this.formData.color,
fuel: this.formData.fuel,
status: this.formData.status,
price: this.formData.price,
};
let requestParameters = { ...utils.globalRequestParameters };
let token = window.localStorage.getItem("token");
requestParameters.headers.Authorization = "Bearer " + token;
requestParameters.method = "PUT";
requestParameters.body = JSON.stringify(data);
fetch(utils.url + "cars/" + this.formData.id, requestParameters)
.then((res) => res.json())
.then((res) => {
console.log(res.message);
if (
res.message === "Decoding error!" ||
res.message === "Your token expired!"
) {
console.log("nu ai voie!");
} else {
let newData = {
id: this.formData.id,
vehicle: data.vehicle,
color: data.color,
fuel: data.fuel,
status: data.status,
price: data.price,
};
this.$store.dispatch("editCar", newData);
this.$router.push("/");
}
});
}
},
Also in your mutation cand make something like this:
EDIT_CAR: (state, car) => {
Object.assign(state.cars[state.cars.findIndex(c => c.id === car.id)], car);
}
Can you try to change your EDIT_CAR mutation to:
const index = state.cars.findIndex(x => x.id === car.id)
state.cars.splice(index, 1, car)
If you haven't done already, place a console.log(car) at the beginning of the mutation so you make sure it gets called and the car payload is what you expect.

findOne is not a function

I am trying to create a model using Sequelize and mysql db.I am trying to post to '/students/register' it keeps giving me an error saying findOne is not a function. I tried requiring my sql but it's not working ..I also tried a different function like findAll and still not working.what seems to be the problem
const Sequelize = require('sequelize');
module.exports = function (sequelize, Sequelize) {
const Stundet = sequelize.define(
'student', {
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
name: {
type: Sequelize.STRING
},
email: {
type: Sequelize.STRING
},
password: {
type: Sequelize.STRING
},
created: {
type: Sequelize.DATE,
defaultValue: Sequelize.NOW
}
}, {
timestamps: false
});
module.exports = Stundet;
}
routes
const Student_Info = require("../models/students")
student.post('/register', (req, res) => {
const dataToday = new Date()
const studentData = {
name: req.body.name,
email: req.body.email,
password: req.body.password,
created: dataToday
}
Student_Info.findOne({
where: {
email: req.body.email
}
})
.then(student => {
if (!student) {
bcrypt.hash(req.body.password, 10, (err, hash) => {
studentData.password = hash
Student_Info.create(studentData)
.then(student => {
res.json({
status: student.email + 'registered'
})
})
.catch(err => {
res.send('error' + err)
})
})
} else {
res.json({
error: 'Student already registered'
})
}
})
.catch(err => {
res.send('error' + err)
})
})
module.exports = student;
When you use module.exports, you should return Stundet. You already export the whole function. And I think you should pass DataTypes instead of Sequelize.
Something like this:
module.exports = function (sequelize, DataTypes) {
const Stundet = sequelize.define(
//...
return Stundet;
}
So in your route in order to use your model:
const Sequelize = require('sequelize');
const DataTypes = sequelize.DataTypes;
let sequelize = new Sequelize(...);
const Student = require('../models/students')(sequelize, DataTypes);
I suspect that your Student_Info is null. Does you application successfully connect to the database? It helps to log... e.g.
sequelizeDB
.authenticate()
.then(() => {
console.log('Yes! DB Connection);
...
})
.catch(err => {
console.error('No! Unable to connect to DB', err);
});
... and IMHO the code reads better when you name the DB instance something other than "sequelize".

Cannot read property of "then" of undefined APOLLO GRAPHQL

I'm having a trouble and i'm stuck. I used to replicate this on my other codes but this method doesn't work on apollo. Here is my method using the apollo on my vue.js.
handleLikePost() {
const variables = {
postId: this.postId,
username: this.user.username
};
this.$apollo.mutate({
mutation: LIKE_POST,
variables,
update: (cache, { data: { likePost } }) => {
const data = cache.readQuery({
query: GET_POST,
variables: { postId: this.postId }
});
data.getPost.likes += 1;
cache
.writeQuery({
query: GET_POST,
variables: { postId: this.postId },
data
})
.then(({ data }) => {
// const updatedUser = {
// ...this.user,
// favorites: data.likePost.favorites
// };
//this.$store.commit("setUser", updatedUser);
console.log(this.user);
console.log(data.likePost);
})
.catch(err => console.error(err));
}
});
}
I think the problem is you are not returning something from;
cache.writeQuery()
That's why .then({data}) is not getting something from writeQuery()

Two custom methods/endpoints using loopBack, one works, the other gives a 401

I created two custom endpoints with Loopback.
Account.deleteAllHearingTests = function (req, callback) {
console.log('here comes the req to delete all hearing tests', req);
Account.findById(req.accessToken.userId)
.then(account => {
if (!account) {
throw new Error('cannot find user');
}
return app.models.HearingTest.updateAll({ accountId: account.id }, { isDeleted: new Date() });
})
.then(() => {
callback(null);
})
.catch(error => {
callback(error);
})
}
Account.remoteMethod(
'deleteAllHearingTests', {
http: {
path: '/clearHearingTests',
verb: 'post'
},
accepts: [
{ arg: 'req', type: 'object', http: { source: 'req' } }
],
returns: {}
}
);
the second one looks like this.
Account.deleteSingleHearingTest = function (req, callback) {
// console.log('accounts.js: deleteSingleHearingTest: are we being reached????', req)
Account.findById(req.accessToken.userId)
.then(account => {
if (!account) {
throw new Error('Cannot find user');
}
console.log('account.js: deleteSingleHearingTest: req.body.hearingTestId N: ', req.body.hearingTestId);
return app.models.HearingTest.updateAll({ accountId: account.id, id: req.body.hearingTestId }, { isDeleted: new Date() });
})
.then(() => {
callback(null);
})
.catch(error => {
callback(error);
});
}
Account.remoteMethod(
'deleteSingleHearingTest', {
http: {
path: '/deleteSingleHearingTest',
verb: 'post'
},
accepts: [
{ arg: 'req', type: 'object', description: 'removes a single hearing test', http: { source: 'req' } }
],
description: 'this is the end point for a single delete',
returns: {}
}
);
};
The first custom method returns a 401 status response when I make the initial fetch. The second returns a 200.
Inside my actions file the first method is called with something that looks like this:
export function deleteAllHearingTests() {
return (dispatch, getState) => {
let state = getState();
if (!state.user || !state.user.accessToken || !state.user.accessToken.id || !state.user.accessToken.userId) {
console.debug('deleteAllHearingTests', state.user);
// TODO: ERROR
return;
}
fetch(SERVERCONFIG.BASEURL + '/api/Accounts/clearHearingTests?access_token=' + state.user.accessToken.id, {
method: 'POST',
headers: SERVERCONFIG.HEADERS
})
.then(response => {
console.log('here is your response', response);
if (response.status !== 200) {
throw new Error('Something is wrong');
}
return response.json()
})
the second method is called with
export const deleteSingleHearingTest = (hearingTestNumber) => {
return (dispatch, getState) => {
let state = getState();
if (!state.user || !state.user.accessToken || !state.user.accessToken.id || !state.user.accessToken.userId) {
console.debug('writeTestResult', state.user);
// TODO: ERROR
return;
}
console.log('single delete ', SERVERCONFIG.BASEURL + '/api/Accounts/deleteSingleHearingTest?access_token=' + state.user.accessToken.id)
fetch(SERVERCONFIG.BASEURL + '/api/Accounts/deleteSingleHearingTest?access_token=' + state.user.accessToken.id, {
method: 'POST',
headers: SERVERCONFIG.HEADERS,
body: JSON.stringify({ "hearingTestId": hearingTestNumber })
})
.then(response => {
console.log('getting response from initial fetch inside deleteSingleReqport', response);
They are nearly identical, however, one works..the other fails. What are some possible causes for the 401?
Did you try to call those methods with external tool like a postman, so you would exactly know if you don't miss access_token or something else? Also, when you compare code from one function and another, you can see that you are colling the updateAll with different arguments. It's hard to say without original code, but maybe the issue is there? Compare below:
return app.models.HearingTest.updateAll(
{ accountId: account.id },
{ isDeleted: new Date() });
return app.models.HearingTest.updateAll(
{ accountId: account.id, id: req.body.hearingTestId },
{ isDeleted: new Date() });
Additionally, in fetch method they are also diffferences, you are missing in one case the below:
body: JSON.stringify({ "hearingTestId": hearingTestNumber })
What you could also do to debug and to provide more data is to run server in debug mode by calling:
export DEBUG=*; npm start

How to access local component variable from a callback in vue?

I am trying to set my components variable using an api rest command. I wanted to handle all responses through a function in its own file called handleResponse() which is below.
// api/tools/index.js
function handleResponse (promise, cb, cbError) {
var cbErrorRun = (cbError && typeof cb === "function")
promise.then(function (response) {
if (!response.error) {
cb(response)
}
else if (cbErrorRun) {
cbError(response)
}
}).catch(function (error) {
console.log(error)
if (cbErrorRun) {
var responseError = {
"status": 404,
"error": true,
"message": error.toString()
}
cbError(responseError)
}
})
}
export {handleResponse}
In my component file I have this
.... More above....
<script>
import { fetchStock } from '#/api/stock'
export default {
data () {
return {
stock: {},
tabs: [
{
title: 'Info',
id: 'info'
},
{
title: 'Listings',
id: 'listings'
},
{
title: 'Company',
id: 'company'
}
],
}
},
validate ({params}) {
return /^\d+$/.test(params.id)
},
created: function() {
var params = {'id': this.$route.params.stockId}
//this.$route.params.stockId}
fetchStock(
params,
function(response) { //on successful data retrieval
this.stock = response.data.payload // payload = {'name': test123}
console.log(response)
},
function(responseError) { //on error
console.log(responseError)
}
)
}
}
</script>
The current code gives me this error: "Uncaught (in promise) TypeError: Cannot set property 'stock' of undefinedAc". I think this happens because I no longer have access to 'this' within the callback I pass in the fetchStock function. How would I fix this without changing the current handleResponse layout.
You can try this trick
created: function() {
var params = {'id': this.$route.params.stockId}
//this.$route.params.stockId}
var self = this;
fetchStock(
params,
function(response) { //on successful data retrieval
self.stock = response.data.payload // payload = {'name': test123}
console.log(response)
},
function(responseError) { //on error
console.log(responseError)
}
)
}
You can either use an arrow function for you callback since arrow functions maintain and use the this of their containing scope:
created: function() {
var params = {'id': this.$route.params.stockId}
//this.$route.params.stockId}
fetchStock(
params,
(response) => { //on successful data retrieval
self.stock = response.data.payload // payload = {'name': test123}
console.log(response)
},
(responseError) => { //on error
console.log(responseError)
}
)
}
Or you can assign const vm = this n the beginning of your method before the callbacks like so.
vm stands for "View Model"
created: function() {
var params = {'id': this.$route.params.stockId}
//this.$route.params.stockId}
const vm = this;
fetchStock(
params,
function(response) { //on successful data retrieval
self.stock = response.data.payload // payload = {'name': test123}
console.log(response)
},
function(responseError) { //on error
console.log(responseError)
}
)
}
I advise using the const as opposed to var in the vm declaration to make it obvious the value of vm is a constant.