its not waiting for validation and just run the else part :| where is my mistake?
async validateBeforeSubmit(event) {
await this.$validator.validateAll().then( result => {
if (result) {
console.log(result); // just log the -> true
// go submit
}else{
console.log(result); // just log the -> false
event.preventDefault();
var elmnt = document.getElementById("drop_zone");
elmnt.scrollIntoView();
}
})
.catch(error=>console.log(error));
},
i'm using veevalidator and i define some custom rules that need afew seconds to resolve:
created() {
this.$validator.extend('unique', {
// getMessage: field => 'At least one ' + field + ' needs to be checked.',
async validate(value, arg) {
arg = arg[0];
let sw = false;
if (arg == 'n_code') {
let data = {
'n_code': value
}
await Axios.post(duplicate_ncode, data, {
headers: { 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content') }
})
.then((response) => {
if (response.data == true) {
sw = true;
}
})
.catch(error => console.log(error));
if (sw) {
return true;
} else {
return false;
}
}
if (arg == 'email') {
let data = {
'email': value
}
await Axios.post(duplicate_email, data, {
headers: { 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content') }
})
.then((response) => {
if (response.data == true) {
sw = true;
}
})
.catch(error => console.log(error));
if (sw) {
return true;
} else {
return false;
}
}
if (arg == 'mobile') {
let data = {
'mobile': value
}
await Axios.post(duplicate_mobile, data, {
headers: { 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content') }
})
.then((response) => {
if (response.data == true) {
sw = true;
}
})
.catch(error => console.log(error));
if (sw) {
return true;
} else {
return false;
}
}
// console.log('questions', value, testProp, options.some((option) => option[testProp]));
// return true;
}
});
}
when user fill all fields it will check 3 api and that need momnets to check.
and i need to await to get the answer but there is somthing wrong which is not working.
please help
I believe what you want to do is:
async validateBeforeSubmit(event) {
try {
const result = await this.$validator.validateAll();
if (result) {
// go submit
} else {
event.preventDefault();
var elmnt = document.getElementById('drop_zone');
elmnt.scrollIntoView();
}
}
catch (e) {
console.log(e);
}
},
Related
I'm using vue-js and i encountered this problem where i call a get all api and then store it in an array. The logic works perfectly fine in the first component, however when i copied literally the exact same code and pasted it in a second component the call for some reason returns an empty array instead of the array of users. Here is the component
import UsersInServiceCenterService from "../services/UsersInServiceCenterService";
import UserService from "../services/UserService";
export default {
name: "service center",
data() {
return {
currentServiceCenter: null,
message: '',
listOfSpecificServiceCenter1: [],
listOfSpecifiedUsers1: [],
id:"",
};
},
methods: {
getServiceCenter(id) {
ServiceCenterService.get(id)
.then((response) => {
this.currentServiceCenter = response.data;
console.log(response.data);
})
.catch((e) => {
console.log(e);
});
},
updateServiceCenter() {
ServiceCenterService.update(this.currentServiceCenter.id, this.currentServiceCenter)
.then((response) => {
console.log(response.data);
this.message = "The service center was updated successfully!";
})
.catch((e) => {
console.log(e);
});
},
deleteServiceCenter() {
ServiceCenterService.delete(this.currentServiceCenter.id)
.then((response) => {
console.log(response.data);
this.$router.push({ name: "service centers" });
})
.catch((e) => {
console.log(e);
});
},
retrieveAllUsersByServiceCenterId(currentServiceCenter){
UsersInServiceCenterService.getAllUsersByServiceCenterId(currentServiceCenter.id)
.then((response) => {
this.listOfSpecificServiceCenter1 = response.data;
console.log(response.data);
})
.catch((e) => {
console.log(e);
});
},
retrieve(){
this.retrieveAllUsersByServiceCenterId(this.currentServiceCenter);
if(this.listOfSpecificServiceCenter1.length!=0){
for(var i =0 ; i<this.listOfSpecificServiceCenter1.length;i++){
UserService.get(this.listOfSpecificServiceCenter1[i].userId)
.then((response) => {
this.listOfSpecifiedUsers1.push(response.data);
console.log(response.data);
})
.catch((e) => {
console.log(e);
});
}
}
this.isEmpty = !this.isEmpty;
},
},
mounted() {
this.message = "";
this.getServiceCenter(this.$route.params.id);
},
};
</script>
getServiceCenter(id) works fine and it returns the service center. However both of the retrieve() and the retrieveAllUsersByServiceCenterId(currentServiceCenter) do not work at all and they return the empty array. Here is the first component which works totally fine with literally the exact same functions.
import UserService from "../services/UserService";
import UsersInServiceCenterService from "../services/UsersInServiceCenterService";
export default {
name: "servicecenters-list",
data() {
return {
serviceCenters: [],
users:[],
currentServiceCenter: null,
currentUser: null,
currentIndex: -1,
currentUserIndex: -1,
id: "",
searchValue: "",
isEmpty: false,
rows: [],
listOfSpecificServiceCenter:[],
listOfSpecifiedUsers:[],
};
},
methods: {
retrieveServiceCenters() {
ServiceCenterService.getAllServiceCenters()
.then((response) => {
this.serviceCenters = response.data;
console.log(response.data);
})
.catch((e) => {
console.log(e);
});
},
retrieveUsers() {
UserService.getAllUsers()
.then((response) => {
this.users = response.data;
console.log(response.data);
})
.catch((e) => {
console.log(e);
});
},
refreshList() {
this.retrieveServiceCenters();
//this.retrieveUsers();
this.currentServiceCenter = null;
this.currentIndex = -1;
//this.currentUser = null;
//this.currentUserIndex = -1;
},
setActiveServiceCenter(servicecenter, index) {
this.currentServiceCenter = servicecenter;
this.currentIndex = index;
},
setActiveUser(user,userIndex){
this.currentUser= user;
this.currentUserIndex = userIndex;
},
// showList(currentServiceCenter){
// for(var i =0;i<currentServiceCenter.users.length;i++){
// }
// },
retrieve(){
this.retrieveAllUsersByServiceCenterId(this.currentServiceCenter);
if(this.listOfSpecificServiceCenter.length!=0){
for(var i =0 ; i<this.listOfSpecificServiceCenter.length;i++){
UserService.get(this.listOfSpecificServiceCenter[i].userId)
.then((response) => {
this.listOfSpecifiedUsers.push(response.data);
console.log(response.data);
})
.catch((e) => {
console.log(e);
});
}
}
this.isEmpty = !this.isEmpty;
},
retrieveAllUsersByServiceCenterId(currentServiceCenter){
UsersInServiceCenterService.getAllUsersByServiceCenterId(currentServiceCenter.id)
.then((response) => {
this.listOfSpecificServiceCenter = response.data;
console.log(response.data);
})
.catch((e) => {
console.log(e);
});
},
addUserToServiceCenter(currentServiceCenter, currentUser) {
var data = {
serviceCenterId: parseInt(this.currentServiceCenter.id),
userId: parseInt(this.currentUser.id),
};
UsersInServiceCenterService.add(data)
.then((response) => {
//this.currentServiceCenter.id = response.data.id; //take care here
console.log(response.data);
this.submitted = true;
})
.catch((e) => {
console.log(e);
});
this.show=false
if(currentServiceCenter.users == Array.isArray(currentServiceCenter.users))
//currentServiceCenter.users = Array.isArray(currentServiceCenters.users) : [...currentServiceCenter.users, currentUser] : [currentUser]
currentServiceCenter.users.push(currentUser);
else{
currentServiceCenter.users = []
currentServiceCenter.users.push(currentUser);
}
},
removeAllServiceCenters() {
ServiceCenterService.deleteAllServiceCenters()
.then((response) => {
console.log(response.data);
this.refreshList();
})
.catch((e) => {
console.log(e);
});
},
searchId(id) {
ServiceCenterService.get(id)
.then((response) => {
this.currentServiceCenter = response.data;
})
.catch((e) => {
console.log(e);
});
this.refreshList();
// if(typeof id ==='string'){
// }
// else if(typeof id==='number'){
// CompanyService.get(id).then(response =>{
// this.currentCompany=response.data
// })
// .catch(e=>{
// console.log(e);
// });
// }
},
},
mounted() {
this.retrieveServiceCenters();
this.retrieveUsers();
},
computed:{
usersFilteredListByName(){
if(this.searchValue.trim().length >0){
return this.serviceCenters.filter((servicecenter) =>servicecenter.name.toLowerCase().includes(this.searchValue.trim()))
}
// if(this.searchValue.length>0 && isNaN(parseInt(this.searchValue))){
// return this.companies.filter((company) =>company.id.includes(this.searchValue))
// }
return this.serviceCenters
},
usersFilteredListById(){
if(this.searchValue.trim().length >0){
return this.serviceCenters.filter((servicecenter) =>servicecenter.id.toString().includes(this.searchValue))
}
return this.serviceCenters
},
}
};
</script>
You can ignore the rest of the functions and focus on the retrieve() and retrieveAllUsersByServiceCenterId(). Any help would be highly appreciated.
beforeTabSwitch: async (tab) => {
let flag = false;
if (tab === 'PAYMENT') {
if (this.isManualValidated) {
flag = true;
this.savePayment().then((response) => {
this.placeOrder();
});
}
}
return flag;
}
savePayment: async function () {
this.$http.post(this.savePaymentRoute)
.then(response => {
await this.getOrderSummary();
})
.catch(error => {
});
},
placeOrder: async function () {
this.$http.post(this.saveOrderRoute)
.then(response => {
})
.catch(error => {
console.log('placeOrder | ' + error);
})
},
When Place Order Button Clicked beforeTabSwitch() which validate data & then call savePayment() . as savePayment request is complete then call getOrderSummary() then call placeOrder() request.
Call in Order: savePayment() > getOrderSummary() > placeOrder()
but the issue is after execute savePayment() immediately placeOrder() execution start after complete then getOrderSummary() execute which is wrong.
i already try with Promises, callback but same issue.
You need to start writing some clean code. And you should either use promises approach or async-await approach. I hope this code help you:
beforeTabSwitch: async (tab) => {
if (tab !== 'PAYMENT') {
return false;
}
if (!this.isManualValidated) {
return false;
}
try {
const response = await this.savePayment();
this.placeOrder();
} catch (error) {
console.log(error);
}
return true;
},
savePayment: async function () {
try {
const paymentResponse = await this.$http.post(this.savePaymentRoute);
const summaryResponse = await this.getOrderSummary();
} catch (error) {
console.log(error);
}
},
placeOrder: async function () {
try {
const response = await this.$http.post(this.saveOrderRoute);
} catch (error) {
console.log('placeOrder | ' + error);
}
},
I have the following functions. The problem I'm having is that the updateInterviewArrays() has a loop in it to fetch and store data, which works. But I need the updateStates and doScoreMath functions called after it to wait, and go in order after it's finished. I can't seem to make that happen though.
componentDidMount() {
this.getScoresFromTables();
}
getScoresFromTables() {
fetch(API_URL + `/interviews/${this.props.auditId}`)
.then((res) => {
if (!res.ok) {
throw new Error();
}
return res.json();
})
.then((result) => {
this.setState({completedInterviews: result}, () => this.updateInterviewArrays());
})
.catch((error) => {
console.log(error);
})
.then(this.updateStates())
.catch((error) => {
console.log(error);
})
.then(this.doScoreMath());
}
updateInterviewArrays() {
const totalInterviews = this.state.completedInterviews.length;
const tableSections = [
'audit_general',
'audit_culture',
'audit_performance',
'audit_policies',
'audit_risk',
'audit_strategy',
'audit_rewards',
'audit_workforce'
];
for (let i = 0; i < totalInterviews; i++){
for (let j = 0; j < 8; j++){
this.grabTableData(tableSections[i], this.state.completedInterviews[j].employee_id);
}
}
}
async grabTableData (tableName, employeeId) {
await fetch(API_URL + `/responses/${tableName}/${employeeId}`)
.then((res) => {
if (!res.ok) {
throw new Error();
}
return res.json();
})
.then((result) => {
if (tableName === "audit_general") {
tableData.audit_general.push(result[0]);
} else if (tableName === "audit_culture") {
tableData.audit_culture.push(result[0]);
} else if (tableName === "audit_performance") {
tableData.audit_performance.push(result[0]);
} else if (tableName === "audit_policies") {
tableData.audit_policies.push(result[0]);
} else if (tableName === "audit_risk") {
tableData.audit_risk.push(result[0]);
} else if (tableName === "audit_strategy") {
tableData.audit_strategy.push(result[0])
} else if (tableName === "audit_rewards") {
tableData.audit_rewards.push(result[0]);
} else if (tableName === "audit_workforce") {
tableData.audit_workforce.push(result[0]);
}
console.log(result);
console.log(tableData);
})
.catch((error) => {
console.log(error);
})
// .then(() => this.updateStates())
// .catch((error) => {
// console.log(error);
// })
// .then(() => this.doScoreMath())
;
}
I was trying to build a PWA with the help of a service worker when it comes to caching, everything went smooth. But I ran into a curious problem. I could not serve my assets with SW when the app is offline. It seems that SW always fails to respond to a 'navigate' request.
Uncaught (in promise) TypeError: Failed to fetch
this.addEventListener('fetch', async event => {
event.respondWith(
(async function() {
const requestObj = event.request;
console.log(event);
const urlParts = requestObj.url.split('/');
const fileName = urlParts[urlParts.length - 1];
const fileExtension = fileName.split('.')[fileName.split('.').length - 1];
if (requestObj.method === 'GET') {
if (requestObj.mode === 'navigate' && event.request.headers.get('accept').includes('text/html')) {
console.log('Navigating', requestObj);
const urlParts = requestObj.url.split('/');
console.log(urlParts);
console.log('looking for another option...');
caches.match(event.request).then(function(response) {
return response || fetch(event.request);
});
}
// If its an image, then save it if it is in '.png' format
if (fileExtension === 'jpg' || requestObj.destination === 'image') {
caches
.match(requestObj)
.then(res => {
if (!res) {
throw new TypeError('Bad response status');
} else {
return res;
}
})
.catch(() => {
fetch(requestObj).then(response => {
console.log(response);
if (response.ok || (response.type === 'opaque' && response.status === 0)) {
caches.open('v1').then(cache => {
cache.put(requestObj, response);
});
}
return response;
});
return fetch(requestObj);
});
}
///////////////////////
if (
requestObj.destination === 'script' ||
requestObj.destination === 'style' ||
requestObj.destination === 'font'
) {
caches
.match(requestObj)
.then(response => {
if (response) {
return response;
} else {
throw new TypeError('Bad response status');
}
})
.catch(() => {
fetch(requestObj).then(res => {
if (res.ok) {
caches.open('v1').then(cache => {
cache.put(requestObj, res);
});
}
return res.clone();
});
});
}
//////////////////////
}
return fetch(requestObj);
})()
);
});
I don't think you need the async function inside the fetch event handler, caches.match returns a promise so it is good enough to be the parameter for the respondWith method
self.addEventListener('fetch', event => {
event.respondWith(
caches.match(event.request).then(function(response) {
const requestObj = event.request;
console.log(event);
const urlParts = requestObj.url.split('/');
const fileName = urlParts[urlParts.length - 1];
const fileExtension = fileName.split('.')[fileName.split('.').length - 1];
if (requestObj.method === 'GET') {
if (requestObj.mode === 'navigate' && event.request.headers.get('accept').includes('text/html')) {
console.log('Navigating', requestObj);
const urlParts = requestObj.url.split('/');
console.log(urlParts);
console.log('looking for another option...');
caches.match(requestObj).then(function(response) {
return response || fetch(event.request);
});
}
// If its an image, then save it if it is in '.png' format
if (fileExtension === 'jpg' || requestObj.destination === 'image') {
caches
.match(requestObj)
.then(res => {
if (!res) {
throw new TypeError('Bad response status');
} else {
return res;
}
})
.catch(() => {
fetch(requestObj).then(response => {
console.log(response);
if (response.ok || (response.type === 'opaque' && response.status === 0)) {
caches.open('v1').then(cache => {
cache.put(requestObj, response);
});
}
return response;
});
return fetch(requestObj);
});
}
///////////////////////
if (
requestObj.destination === 'script' ||
requestObj.destination === 'style' ||
requestObj.destination === 'font'
) {
caches
.match(requestObj)
.then(response => {
if (response) {
return response;
} else {
throw new TypeError('Bad response status');
}
})
.catch(() => {
fetch(requestObj).then(res => {
if (res.ok) {
caches.open('v1').then(cache => {
cache.put(requestObj, res);
});
}
return res.clone();
});
});
}
return fetch(requestObj);
}
})
)
});
I am using meteor/react. I have two components. I want to pass method from one:
saveNewUsername(newUsername) {
Meteor.call('setNewUsername', newUsername, (error) => {
if(error) {
Materialize.toast(error.reason, 4000);
} else {
Materialize.toast('Username changed!', 4000);
}
});
}
And than I need to check it for success:
handleSaveOption() {
const { howToChangeOption } = this.props;
const optionValue = this.option.value.trim();
if(howToChangeOption(optionValue)) {
this.setState((prevState) => ({
startToChange: !prevState.startToChange,
}));
}
}
So, how to check Meteor.call for success and return true or false? Thanks!
Solved with promises. Maybe anyone has better solution?
saveNewUsername(newUsername) {
return new Promise((resolve, reject) => {
Meteor.call('setNewUsername', newUsername, (error) => {
if(error) {
Materialize.toast(error.reason, 4000);
reject();
} else {
Materialize.toast('Username changed!', 4000);
resolve();
}
});
});
}
handleSaveOption() {
const { howToChangeOption } = this.props;
const optionValue = this.option.value.trim();
howToChangeOption(optionValue).then(() => {
this.setState((prevState) => ({
startToChange: !prevState.startToChange,
}));
});
}