Check for duplicates before saving them on database - javascript

I'm pretty new to coding and to Velo from Wix, therefore I need help.
I created a member's page, the page gets the pricing plan that the member subscribed to, and it shows a specific form to be submitted in order to set a dashboard according to the region he/she selects.
When the user submits the form, my code checks for duplicates like email and field values. If the user has already submitted it an error will appear telling the user that the form was already submitted, if the value is "" or equal to another one, another message will appear and tells the user to check the selection and make 3 different selections.
Well for the Free Plan where only one dropdown is shown, everything runs smoothly, for the Basic where I have 3 dropdowns nothing works. So... let' go to the code:
import wixData from 'wix-data';
import wixUsers from 'wix-users';
$w.onReady(function () {
console.log("Ready")
let user = wixUsers.currentUser
user.getPricingPlans()
.then ((pricingPlans) => {
let firstPlan = pricingPlans[0];
let planName = firstPlan.name;
if (planName == '7 DAY FREE TRIAL $0'){
$w('#text30').show();
$w("#text31").show();
$w('#dropdown1').show();
$w('#emailInput').show();
$w('#button1').show();
searchForDuplicityFreePlan();
}
if(planName == 'BASIC'){
$w('#text30').show();
$w("#text31").show();
$w('#dropdown2').show();
$w('#dropdown3').show();
$w('#dropdown4').show();
$w('#emailInput2').show();
$w('#button2').show();
searchForDuplicityBasicPlan();
}
});
});
async function searchForDuplicityFreePlan(){
$w("#dataset1").onBeforeSave(async() => {
let checkEmailFreeOk = await checkEmailFree();
let fieldCheck = $w("#dropdown1").value;
if(checkEmailFreeOk === false){
$w("#text32").text = "An error occurred. You have already submitted this form";
return false
}
if(fieldCheck === ""){
$w("#text32").text = "An error occurred. Please select your region of interest";
return false
}
})
}
async function checkEmailFree(){
let flagFree = true
await wixData.query('RegionSelectionQuizFree')
.eq('email', $w("#emailInput").value)
.find()
.then((result)=>{
if(result.items.length > 0)
flagFree = false
})
return await flagFree
}
async function searchForDuplicityBasicPlan(){
$w("#dataset2").onBeforeSave(async() => {
let checkEmailBasicOk = await checkEmailBasic();
let region1 = $w("#dropdown2").value;
let region2 = $w("#dropdown3").value;
let region3 = $w("#dropdown4").value;
const regions = new Set();
regions.add(region1);
regions.add(region2);
regions.add(region3);
regions.delete("");
if(checkEmailBasicOk === false){
$w("#text34").text = "An error occurred. You have already submitted this form";
return false
}
if (regions.size !== 3) {
$w("#text34").text = "An error occurred. Please select 3 different regions of interest";
return false
}
})
}
async function checkEmailBasic(){
let flagBasic = true
await wixData.query('RegionSelectionQuizBasic')
.eq('email', $w("#emailInput2").value)
.find()
.then((result)=>{
if(result.items.length > 0)
flagBasic = false
})
return await flagBasic
}

Related

my functions are mixed and the engine executing what ever he wants

so i was told to Present a loader to the user when a call is made to the server (indicating the server is calculating) Present an error to the user if the input number is more than 50, and do not send a server request Try passing the number 42 to the server. The server will send back an error, present this error to the user.
now what i did is everything besides the last error to present it to the user.
i have tried everything i could think of, and no matter what the user types, it displays both of the messages.
this is my code:
const clcBtn = document.getElementById("calcButton");
let clcInput = document.getElementById("calcInput");
const result = document.getElementById('paragraph');
const loader = document.getElementById('spinner');
const error = document.getElementById('error-message');
const serverError = document.getElementById('server-error');
clcBtn.addEventListener("click", calcFunc);
function numValidate(value) {
if(value > 50) {
return false;
}
return true;
}
function calcFunc() {
if (!numValidate (clcInput.value)) {
error.style.display = "block"
setTimeout(() => {
error.style.display = "none";
}, 5000);
console.error("Can't be larger than 50") // only bec it's a cool feature :D
return;
}
loader.classList.add("spinner-border");
fetch(`http://localhost:5050/fibonacci/${clcInput.value}`).then(function (response) {
return response.json().then(function (data) {
result.innerHTML = data.result;
});
});
setTimeout(() => {
loader.classList.remove("spinner-border");
}, 1000);
}
this is my code with what i have tried to add (on of the things i have tried.. this is the best output i could come with)
code:
// additional code to present to the user the error message if the input value is equal to 42.
clcBtn.addEventListener("click", errMsg);
function numValidateTwo(value) {
if(value === 42) {
return true;
}
return false;
}
function errMsg() {
if (!numValidateTwo (clcInput.value)) {
serverError.style.display = "block";
}
return;
}
a little bit more about what i am trying to achieve:
i want to present this error message to the user, whenever the input value is equal to 42.
is it related to async or callback? which i need to go through the lectures again.. but right now i need to solve this bec i have no time.
what did i do wrong ?
and how i can make it work?
can someone explain this to me?
thanks in advance!

Initial load and when I change value of input doesn't show message in JavaScript

everyone, I have some problem with fetching data and displaying message on initial loading as well as when I change some of the input filed value. The idea here is to display specific message in two cases after doing some calculation.
const potrosnja = document.getElementById('potrosnja');
const nagib = document.getElementById('nagib');
const input = document.querySelectorAll('input[type="number"]');
const submitBtn = document.getElementById('submitBtn');
const poruka = document.getElementById('poruka');
let str = document.querySelector('input[name="strane-sveta"]:checked').value;
let godisnjaPotrosnja = parseInt(potrosnja.value);
let nagibKrovaInput = nagib.value;
//On button submit it fetches data and calculate the value needed for yearly consumption of energy
//fetching data
async function dataFetch(){
let response = await fetch('./csvjson.json')
let data = await response.json();
data.map(strana => {
strana.strana.map((item, i) => {
try {
if(item == str && nagibKrovaInput == strana.nagib) {
let result = Math.ceil(godisnjaPotrosnja / strana.vrednost[i]);
console.log("try works")
poruka.innerHTML = `You need <span class="kw">${result}</span>`
}
}
catch(err) {
poruka.innerHTML = `Please fill required fields.`
console.log(err)
}
})
})
}
//event listeners
submitBtn.addEventListener('click', () => {
dataFetch()
console.log('clicked')
input.forEach(input => {
if(input.value == ''){
input.classList.add("active");
}
})
})
I can see that the problem is inside try function, it like condition isn't treated on initial load, and I have to reload page so it would work. Can someone help me understanding what is the problem?
Ok, I found solution... First thing I have to do Is to check if nagibKrovaInput == strana.nagib, after I get true, I compared does the indexOf item is equal as str and after I get true, it will display something. I also changed on click on the button to send values to data function as an arguments and It solved the problem. Tnx for help.

Trying to get the elements of a page when it fully loads but I either get undefined or null. Why?

I've been working on this for two days now and I still can't figure out why my elements are sometimes either returning null or other times returning undefined but never returning the properties themselves. I've set their ID's in the respective HTML file and I still get null or undefined.
I've tried using setTimeout() but that didn't work because I was redirecting to a new page. I tried using an event listener on the document with DOMContentLoaded. I've even tried window.onload
var userEmailDisplay;
var newPaswordInput;
var confNewPaswordInput;
var submitNewPasswordBtn;
const urlParams = getAllUrlParams(window.location.href);
const actionCode = urlParams.oobCode;
window.onload = () => {
var doc = document;
switch (urlParams.mode) {
case 'resetPassword':
handleResetPassword(actionCode);
break;
case 'recoverEmail':
handleRecoverEmail(actionCode);
break;
case 'verifyEmail':
handleVerifyEmail(actionCode);
break;
}
// get new password elements
/* if (window.location.href.indexOf("new-password") > -1) {
userEmailDisplay = doc.getElementById('account-email-new-pswd');
newPaswordInput = doc.getElementById('new-password-input');
confNewPaswordInput = doc.getElementById('conf-new-password-input');
submitNewPasswordBtn = doc.getElementById('update-pswd-sub-btn');
} */
}
function handleResetPassword(actionCode) {
// Verify the password reset code is valid.
auth.verifyPasswordResetCode(actionCode).then(function (email) {
window.location.href = "https://couch-potato-880f0.firebaseapp.com/email/new-password.html";
console.log("code verified");
confirmThePswdReset(actionCode, email);
}).catch(function (error) {
console.error(error);
});
}
function confirmThePswdReset(actionCode, email) {
window.onload = () => {
userEmailDisplay = document.getElementById('account-email-new-pswd');
newPaswordInput = document.getElementById('new-password-input');
confNewPaswordInput = document.getElementById('conf-new-password-input');
submitNewPasswordBtn = document.getElementById('update-pswd-sub-btn');
console.log(submitNewPasswordBtn + ' + ' + userEmailDisplay);
if (submitNewPasswordBtn && userEmailDisplay) {
submitNewPasswordBtn.addEventListener('click', function (e) {
e.preventDefault();
const accountEmail = email;
console.log('submit btn clicked');
const newPassword = newPaswordInput.value;
const confNewPasswordValue = confNewPaswordInput.value;
userEmailDisplay.innerHTML = `Email: ${accountEmail}`;
if (newPassword != confNewPasswordValue) {
alert('The new passwords must match!');
return;
}
console.log(newPassword);
// Save the new password.
auth.confirmPasswordReset(actionCode, newPassword).then(function (resp) {
// Password reset has been confirmed and new password updated.
alert("All good");
window.location.replace('/email/confirm-password-reset.html');
}).catch(function (error) {
console.error(error);
});
});
}
}
}
I expect when I click the submit button on the new password page, there's the alert box to pop up saying that everything is good and the password has been reset but that never happens. The code only goes up to the if-statement that checks if submitNewPasswordBtn and userEmailDisplay exist and are not null. I know that because I never get an output log saying that the submit button was clicked. Sometimes I never even get the output checking that submitNewPasswordBtn and userEmailDisplay exist and have values.

if else in loop bringing up errors in typescript

I have this function that is supposed to get referral codes from users. User gives a code and the referral code checked if it exists in the database then evaluated if
it does not match the current user, so that one should not refer himself and
it is a match with one of the codes in the database
This code however just does not find a match even if the code given is in the database. If the referral code matches the one of the current user, it works correctly and points that out i.e one cannot refer themselves.
But if the referral code is a match to that of another user which is how a referral system should work, it still says no match.
How can I remove this error
export const getID = functions.https.onCall(async(data, context) => {
const db = admin.firestore();
const usersSnapshot = await db.collection("user").get();
const allUIDs = usersSnapshot.docs.map(doc => doc.data().userID);
const userID = context.auth.uid;
const providedID = "cNx7IuY6rZlR9mYSfb1hY7ROFY2";
//db.collection("user").doc(providedID).collection("referrals").doc(userID);
await check();
function check() {
let result;
allUIDs.forEach(idFromDb => {
if (providedID === idFromDb && (idFromDb === userID)) {
result = "ownmatch";
} else if (providedID === idFromDb && (idFromDb !== userID)) {
result = "match";
} else {
result = "nomatch";
}
});
return result;
}
if (check() === "match") {
return {
message: `Match Found`,
};
} else if (check() === "ownmatch") {
return {
message: `Sorry, you can't use your own invite code`,
};
} else {
return {
message: `No User with that ID`
};
}
});
(This is not an answer, but a simple refactoring.)
This is what your code is currently doing (roughly, I didn't run it):
const resultMsgs = {
nomatch: 'No User With That ID',
ownmatch: 'Sorry, you can\'t use your own invite code',
match: 'Match Found',
}
function check(uids, providedId, userId) {
let result
uids.forEach(idFromDb => {
if (providedId !== idFromDb) {
result = 'nomatch'
return
}
if (userID === idFromDb) {
result = 'ownmatch'
return
}
result = 'match'
})
return result
}
export const getID = functions
.https
.onCall(async (data, context) => {
const userId = context.auth.uid
const providedId = 'cNx7IuY6rZlR9mYSfb1hY7ROFY2'
const db = admin.firestore()
const user = await db.collection('user').get()
const uids = user.docs.map(doc => doc.data().userId)
const checkResult = check(uids, providedId, userId)
return { message: resultMsgs[checkResult] }
})
(I removed the seemingly-spurious db collection operation.)
Your forEach is iterating over all of the uuids, but result will be set to whatever the last comparison was. Perhaps this is correct, but:
If you're looking for any match, this is not what you want.
If you're looking for all matches, this is not what you want.
If you're looking to match the last UUID, it's what you want, but an odd way to go about it.
So:
If you want any matches, use... ahem any form of an any function.
If you want all matches, use any form of an all function.
If you want the first match, then just check the first element.
If you want the complete set of comparisons then you'll need to use map instead of forEach, and handle each result appropriately, whatever that means in your case.
In any event, I'd recommend breaking up your code more cleanly. It'll be much easier to reason about, and fix.

Else statement still running when if statement is true

I have search functionality that allows you to search for cryptocurrencies and I'm trying to have it where if the param/coin that is searched doesn't match with the API's title of the coin or symbol, an alert box would pop up telling the user to try again.
The problem I'm having is that if the if statement is true and there's a match, the else statement/alert box pops up regardless. Here's my code within my axios request:
cryPrice(param){
axios.get(`https://api.coinmarketcap.com/v1/ticker/?limit=0`)
.then(res => {
const cryptos = res.data;
const price = []
for(let title in cryptos){
const cryptoTitle = cryptos[title].name.toUpperCase();
const cryptoSymbol = cryptos[title].symbol.toUpperCase();
if(cryptoTitle === param || cryptoSymbol === param){
price.push(cryptos[title].price_usd);
}else{
alert("Please try again");
break;
}
}
this.setState({
priceResults: price
})
})
}
Your code loops through every single item in the array, as soon as a non-matching item is encountered it alerts and breaks the loop
What you probably want is more like
cryPrice(param){
axios.get(`https://api.coinmarketcap.com/v1/ticker/?limit=0`)
.then(res => {
const priceResults = res.data
.filter(item => [item.name.toUpperCase(), item.symbol.toUpperCase()].includes(param))
.map(item => item.price_usd);
if (priceResults.length) {
this.setState({priceResults});
} else {
alert("Please try again");
}
})
}
You find a match on some of the elements but alert about every other, all of those that do not match param. You should probably only alert after the loop execution has stopped and iff there were no currencies matched.

Categories