Code Review Friday: Let's Improve your code, ask Corvid master

June 5th, 2020
Join this week code review organized by Corvid master,
Comment your code below(as per instruction) we will analyze provide you suggestion or refactored code that will be easy to read, to modify, and plenty of good practice.

We also welcome experience corvid forum members to share the knowledge and expertise.

Instructions:

*1: FULL PAGE CODE is recommended
*2: Include database structure like Collection name & Field type (if you refer them in the code)
3: Is this a live site? If so, drop a link so, we can check the code.
4: Videos or Images for explanation of what the code does is useful!
Marked * are required

Don’ts

1: Do NOT include any sensitive code (like passwords, secrect key).

// try to rewrite it as xxx if it's used inside the code
const key = "XXX-XXX";

2: Asking any questions unrelated to code review or corvid
3: Screenshot the code and not pasting the code in text format
4: Code that was not working before and asking to fix (Please create a new post in the community, This Post is dedicated to improve your current working code)

Notes

  • We do code review every friday PST timezone!
2 Likes

hi, I have issue with this code, the first part works perfectly up to the dropdown2 enable, from there it doesn’t work and I can’t see the dropdown data… can you help me out with it?
import wixData from ‘wix-data’ ;

$w.onReady( function () {
uniqueDropDown1();
});

function uniqueDropDown1() {
wixData.query( ‘Kraj’ )
.limit( 1000 )
.find()
.then(results => {
const uniqueTitles = getUniqueTitles(results.items);
$w( “#dropdown1” ).options = buildOptions(uniqueTitles);
});

function getUniqueTitles(items) {
const titlesOnly = items.map(item => item.kraj);
return [… new Set(titlesOnly)];
}

function buildOptions(uniqueList) {
return uniqueList.map(curr => {
return { label: curr, value: curr };
});
}
}

export function dropdown1_change(event, $w) {
uniqueDropDown2();
$w( “#dropdown2” ).enable();
}
function uniqueDropDown2() {
wixData.query( ‘Mesto’ )
.contains( “Kraj” , $w( “#dropdown1” ).value)
.limit( 1000 )
.find()
.then(results => {
const uniqueTitles = getUniqueTitles(results.items);
$w( “#dropdown2” ).options = buildOptions(uniqueTitles);
});

function getUniqueTitles(items) {
const titlesOnly = items.map(item => item.mesto);
return [… new Set(titlesOnly)];
}

function buildOptions(uniqueList) {
return uniqueList.map(curr => {
return { label: curr, value: curr };
});

} 

}

export function dataset1_itemValuesChanged() {
//Add your code for this event here:
}

Hi salman, i have an issue with this code.
The function “clear” doesn’t work properly and secondly i would like to add a function “select all” to the $w( ‘#checkGFirm’ ).options

import wixData from ‘wix-data’ ;
import {local} from ‘wix-storage’ ;

let columns = [{
“id” : “col1” ,
“dataPath” : “firm” ,
“label” : “Firm” ,
“type” : “string”
}]

$w.onReady( function () {
init();

});
async function init() {
let data = ( await wixData.query( “stores” )
.limit( 1000 )
.find()).items;
buildCat();
// console.log(data);

let firmOptions = noDublicate(data.map(el => el.firm));
let proOptions = noDublicate(data.map(el => el.product));

$w( '#checkGFirm' ).options = buildOptions(firmOptions); 

// $w(‘#checkGPro’).options = buildOptions(proOptions);

$w( '#btnSearch' ).onClick(filter); 
$w( '#btnClear' ).onClick(clear); 

$w( '#repeater1' ).onItemReady(($item, itemData, i)=>{ 
    $item( '#textCat' ).text = itemData.catName; 
    $item( '#checkGProd' ).options = buildOptions(itemData.proOptions); 
}); 

$w( '#boxFirm' ).onClick(()=>toggleCollapse( "checkGFirm" )); 
$w( '#boxPro' ).onClick(()=>toggleCollapse( "repeater1" )); 

// restrict 6 products
let maxPro = 6 ;
let lastCats = {};
$w( ‘#checkGProd’ ).onChange(el=>{
let {prods, cats} = getProd();

if (prods.length > 6 ) {
$w( ‘#repeater1’ ).forEachItem(($item, itemData, i) =>{
let cat = itemData.catName;

let lastProds = lastCats[cat];
$item( ‘#checkGProd’ ).value = lastProds;
});
} else {
lastCats = cats;
}

}); 

}

async function filter() {
$w( ‘#textLoading’ ).show();

let {prods} = getProd();
let isValid = validation(prods);
if (isValid !== “true” ) {
$w( ‘#textLoading’ ).text = isValid;
$w( ‘#textLoading’ ).show()
return ;
}
let checkGFirm = $w( ‘#checkGFirm’ ).value;
let checkGPro = prods; //$w(‘#checkGPro’).value;

checkGPro.forEach((el, i) => { 
    columns.push({ 
        id:  "col"  + (i +  2 ), 

“dataPath” : el,
“label” : el,
“type” : “string”
});
});

$w( '#table' ).columns = columns; 

// build columns for table
let rows = await getStores(checkGFirm, checkGPro)
$w( ‘#table’ ).rows = rows;

$w( '#table' ).show(); 
$w( '#textLoading' ).hide(); 

}

function clear() {
$w( ‘#checkGFirm’ ).selectedIndices = [];
// $w(‘#checkGPro’).selectedIndices = [];
$w( ‘#checkGProd’ ).selectedIndices = [];
filter();
}

function validation(prods) {
if ($w( ‘#checkGFirm’ ).selectedIndices.length === 0 ) {
return “Select atleast one firm” ;
}
if (prods < 1 ) {
return “Select atleast two product” ;
}

columns = [{ 

“id” : “col1” ,
“dataPath” : “firm” ,
“label” : “Firm” ,
“type” : “string”
}]
return “true” ;
}

async function getStores(firms, products) {
try {
let res = await wixData.query( “stores” )
.hasSome( “product” , products)
.hasSome( “firm” , firms)
.limit( 1000 )
.find()

    console.log( "data found : " , res, res.length); 

// build rows
let data = res.items;

let uniqueRows = [];
data.forEach(row => {

let firmsUni = uniqueRows.map(el => el.firm);
let pos = firmsUni.indexOf(row.firm);
if (pos === - 1 ) {
uniqueRows.push({
firm: row.firm
});
pos = firmsUni.length
}

        columns.forEach(col => { 

let colKey = col.dataPath;
if (colKey === “firm” ) return ;
if (colKey === row.product) {
uniqueRows[pos][colKey] = row.price;
}
});
});

let rows = [];

    uniqueRows.forEach(uniRow => { 

let row = {};
columns.forEach(el => {
let colKey = el.dataPath;
if (colKey === “firm” ) {
row[ “firm” ] = uniRow[colKey];
return
}
if (colKey !== “firm” && uniRow[colKey]) {
row[colKey] = uniRow[colKey];
} else {
row[colKey] = “not available” ;
}
});
rows.push(row);

    }); 

    rows.sort((a, b) => a.firm.localeCompare(b.firm)); 

// console.log("rows: ", uniqueRows, rows);
return rows;
} catch (err) {
console.log( "Error : " , err.message);
}
}

async function buildCat() {
let cats = ( await wixData.query( “stores” )
.limit( 1000 )
.find()).items;

let repeaterCat = []; // [{categoryName:categoryName, productsOpt:productsOpt }]

let repeaterObj = {}; // {catName : []}
cats.forEach(el=>{
console.log(el);
if (!repeaterObj[el.category]) repeaterObj[el.category] = [];
repeaterObj[el.category].push(el.product);
});
console.log( "repeaterObj : " , repeaterObj);

Object.keys(repeaterObj).forEach((key, i)=>{ 

let obj = {};
obj._id = String(i);
obj.catName = key;
obj.proOptions = noDublicate(repeaterObj[key]).sort();
repeaterCat.push(obj);
});

$w( '#repeater1' ).data = repeaterCat; 



console.log( "cats : "  , cats); 

}

function getProd() {
let prods = [];
let catsObj= {};

$w( '#repeater1' ).forEachItem(($item, itemData, i)=>{ 

let checkedPro = $item( ‘#checkGProd’ ).value;
let cats = itemData.catName;
prods = […prods, …checkedPro];
catsObj[cats] = checkedPro
});
console.log( "prods : " , prods);
return {prods, cats : catsObj};
}

// helper function
function noDublicate(dubArr) {
return Array. from ( new Set(dubArr)).sort();
}

function buildOptions(arr) {
return arr.map(el => ({ label: el, value: el }))
}

function toCamelCase(str) {
return str.toLowerCase().replace(/[^a-zA-Z0-9]+(.)/g, (m, chr) => chr.toUpperCase());
}

function toggleCollapse(id) {
console.log( “click” , id);
if ($w( ‘#’ + id).collapsed) {
$w( ‘#’ + id).expand();
} else {
$w( ‘#’ + id).collapse();
}
}
function dynamicSort(property) {
var sortOrder = 1 ;
if (property[ 0 ] === “-” ) {
sortOrder = - 1 ;
property = property.substr( 1 );
}
return function (a,b) {
/* next line works with strings and numbers,
* and you may want to customize it to your needs
*/
var result = (a[property] < b[property]) ? - 1 : (a[property] > b[property]) ? 1 : 0 ;
return result * sortOrder;
}
}

Hi Salman,
I need buttons to show/hide on 4 different membership plan status:

  1. ACTIVE

  2. CANCELED

  3. SUSPENDED

  4. UNDEFINED
    Unfortunately only status CANCELED works.
    Console error says: TypeError: Cannot read property ‘planName’ of undefined

How can I refer to UNDEFINED? Why are ACTIVE/SUSPENDED not working?

import wixUsers from ‘wix-users’ ;
import wixPaidPlans from ‘wix-paid-plans’ ;

$w.onReady( function () {

let user = wixUsers.currentUser;
let userId = user.id;
let isLoggedIn = user.loggedIn;

wixPaidPlans.getCurrentMemberOrders()
.then ( orders => {
let plan = orders[ 0 ];
let paket = plan.planName;
let stat = plan.status;
let aktivseit = plan.validFrom;
let aktivbis = plan.validUntil;
$w( “#statusv” ).text = stat;
$w( “#paketv” ).text = paket;
$w( “#aktivv” ).text = aktivseit.toString();
$w( “#expiryv” ).text = aktivbis.toString();

if (plan.status=== “ACTIVE” ) {
$w( “#resume” ).hide();
$w( “#pause” ).show();
}
else if (plan.status=== “CANCELED” ) {
$w( “#resume” ).hide();
$w( “#pause” ).hide();
}
else if (plan.status=== “SUSPENDED” ) {
$w( “#resume” ).show();
$w( “#pause” ).hide();
}
else {
$w( “#box1” ).hide();
}
})
. catch ( (err) => {
console.log(err); })
})

The code looks good to me
add a console log at the end
double check the fieldkey n ddatabase permission

function uniqueDropDown2() {
wixData.query( ‘Mesto’ )
.contains( “Kraj” , $w( “#dropdown1” ).value)
.limit( 1000 )
.find()
.then(results => {
console.log( “found :” , results)

Hey this post is only for REFACTORING code
It’s diffcult to fix the bug just by reading through the code or add any feature to it
feel free to create a new POST realted to the BUG

Hey this post is only for REFACTORING code
feel free to create a new POST realted to the BUG

and related the issue this occurs cause there is no Plan for member

you can add code
if(typeof plan === “undefined”) {
console.log(“plan is undefined”)
}

Can someone help me reduce this code in complexity? The code is for a [quiz:](quiz:
https://www.nordicelysium.com/psi

I)
[https://www.nordicelysium.com/psi](quiz:
https://www.nordicelysium.com/psi

I)

[I](quiz:
https://www.nordicelysium.com/psi

I) have tried to put things in the backend but it is not working.

// For full API documentation, including code examples, visit Velo API Reference - Wix.com
import wixData from ‘wix-data’ ;
import wixUsers from ‘wix-users’ ;
import wixLocation from ‘wix-location’ ;
import {names} from ‘backend/constants’ ;

//…

$w.onReady( function () {
//TODO: write your page related code here…
//Display users name, email and ID
let userName;
let userEmail;
let userAge;
let userAddress;
let userSex;
let country;
let cd1; //cd1=cardiovascular disease
let c1; //c1=cancer
let r1; //r1=respiratory diseases
let d1; //d1=diabetes DM type II
let br1; //br1=brain
let ac1; //ac1=accidents
let dr1; //dr1=drug abuse
let l1; //l1=lifeSpan
let i1; //i1=infection
let su1; //s1=suicide

wixData.query( "Members" )  //Get current name, email, age, address, sex and adress from members. 
    .eq( "_owner" , wixUsers.currentUser.id) 
    .find() 
    .then((results) => { 
        userName = results.items[ 0 ].userName; 
        userEmail = results.items[ 0 ].userEmail; 
        userAge = parseFloat(results.items[ 0 ].userAge); 
        userAddress = results.items[ 0 ].userAddress; 
        userSex = results.items[ 0 ].userSex; 
        country = results.items[ 0 ].userAddress.country; 
    }) 
    .then(() => { 
        wixData.query( "elysiumLife" ) 
            .contains( "title" , country) 
            .find() 
            .then((results2) => { 
                cd1 = parseFloat(results2.items[ 0 ].cardiovascularDisease); 
                c1 = parseFloat(results2.items[ 0 ].cancer); 
                r1 = parseFloat(results2.items[ 0 ].respiratoryDisease); 
                i1 = parseFloat(results2.items[ 0 ].infection); 
                d1 = parseFloat(results2.items[ 0 ].diabetesMellitus); 
                br1 = parseFloat(results2.items[ 0 ].brain); 
                ac1 = parseFloat(results2.items[ 0 ].accidents); 
                dr1 = parseFloat(results2.items[ 0 ].drugAbuse); 
                su1 = parseFloat(results2.items[ 0 ].suicide); 

if (userSex === “Male” ) {
l1 = parseFloat(results2.items[ 0 ].maleLifespan);
} else {
l1 = parseFloat(results2.items[ 0 ].femaleLifespan);
}
})
. catch ((error) => {
wixData.query( “elysiumLife” )
.contains( “title” , “WO” )
.find()
.then((world) => {
cd1 = parseFloat(world.items[ 0 ].cardiovascularDisease);
c1 = parseFloat(world.items[ 0 ].cancer);
r1 = parseFloat(world.items[ 0 ].respiratoryDisease);
i1 = parseFloat(world.items[ 0 ].infection);
d1 = parseFloat(world.items[ 0 ].diabetesMellitus);
br1 = parseFloat(world.items[ 0 ].brain);
ac1 = parseFloat(world.items[ 0 ].accidents);
dr1 = parseFloat(world.items[ 0 ].drugAbuse);
su1 = parseFloat(world.items[ 0 ].suicide);
if (userSex === “Male” ) {
l1 = parseFloat(world.items[ 0 ].maleLifespan);
} else {
l1 = parseFloat(world.items[ 0 ].femaleLifespan);
}
})
})
})
//Single-selection of tags
let SelectionTags = $w( ‘SelectionTags’ );
SelectionTags.forEach(selectedTags => {
let prevSelectedValue = null ;
if (selectedTags.value.length === 1 ) {
prevSelectedValue = selectedTags.value[ 0 ];
} else if (selectedTags.value.length > 1 ) {
selectedTags.value = ;
// If multiple tags are selected by default, deselect all of them
//(since there’s no good reason to prefer one of them over the others).
}
selectedTags.onChange((event) => {
// Prevent deselecting the only selected tag.
//Radio buttons do not allow it so tags shouldn’t either.
if (!event.target.value || event.target.value.length === 0 ) {
// Re-apply the previously selected tag.
event.target.value = [prevSelectedValue];
} else {
event.target.value = event.target.value.filter(x => x !== prevSelectedValue);
// Replace the previously selected tag with the newly selected one.
prevSelectedValue = event.target.value[ 0 ];
}
//Change slides on selection smokeTags1
const currTagId = event.target.id;
if (currTagId === “smokeTags1” ) {
if (prevSelectedValue === “3” ) {
$w( ‘#quizSlides’ ).changeSlide( 13 );
} else {
//Change slides on selection on smokeTags1 if “No” is NOT selected
$w( ‘#quizSlides’ ).next();
} //Change slides on selection trainTags6
} else if (currTagId === “trainTags6” ) {
if (prevSelectedValue === “0” ) {
$w( ‘#quizSlides’ ).changeSlide( 23 );
} else {
$w( ‘#quizSlides’ ).next();
} //Change slides on selection alcoholTags1
} else if (currTagId === “alcoholTags1” ) {
if (prevSelectedValue === “3” ) {
$w( ‘#quizSlides’ ).changeSlide( 27 );
} else {
$w( ‘#quizSlides’ ).next();
}
} else {
//Change slides on selection
$w( ‘#quizSlides’ ).next();
}
$w( ‘#elysiumDataPsi’ ).onReady(() => {
//load selectedTagsNum into database
let m1 = parseFloat($w( ‘#mindTags1’ ).value); //“How is your mood?”
let m2 = parseFloat($w( ‘#mindTags2’ ).value); //“What occupies your mind most?”
let m3 = parseFloat($w( ‘#mindTags3’ ).value); //“What is your focus of mindset?”
let m4 = parseFloat($w( ‘#mindTags4’ ).value); //“How much sleep do you get per day?”
let m5 = parseFloat($w( ‘#mindTags5’ ).value); //“How is the quality of your sleep?”
let m6 = parseFloat($w( ‘#mindTags6’ ).value); //“How often do you feel well-rested?”
let m7 = parseFloat($w( ‘#mindTags7’ ).value); //“How often do you feel happy?”
let m8 = parseFloat($w( ‘#mindTags8’ ).value); //“How often do you feel stressed?”
let m9 = parseFloat($w( ‘#mindTags9’ ).value); //“How often do you meditate?”"
let mm1 = parseFloat(m1 + m2 + m3 + m4 + m5 + m6 + m7 + m8 + m9); //sum of all mindscores
let ms1 = parseFloat((mm1 / 27 ) * 100 ).toFixed( 1 );
let s1 = parseFloat($w( ‘#smokeTags1’ ).value); //“Do you smoke tobacco?”
let s2 = parseFloat($w( ‘#smokeTags2’ ).value); //“What type of tobacco?”
let s3 = parseFloat($w( ‘#smokeTags3’ ).value); //“How many units per smoking session?”"
let s4 = parseFloat($w( ‘#smokeTags4’ ).value); //“How often do you smoke?”
if (s1 === 3 ) {
s2 = 3 ;
s3 = 3 ;
s4 = 3 ;
}
let sm1 = parseFloat(s1 + s2 + s3 + s4); //sum of all smokescores
let ss1 = parseFloat((sm1 / 12 ) * 100 ).toFixed( 1 );
let t1 = parseFloat($w( ‘#trainTags1’ ).value); //“How physically active are you?”
let t2 = parseFloat($w( ‘#trainTags2’ ).value); //“How much walking per day?”
let t3 = parseFloat($w( ‘#trainTags3’ ).value); //“Do you take the stairs?”
let t4 = parseFloat($w( ‘#trainTags4’ ).value); //“What do you prefer for transport?”
let t5 = parseFloat($w( ‘#trainTags5’ ).value); //“Physical demands of your work?”
let t6 = parseFloat($w( ‘#trainTags6’ ).value); //“Do you workout?”
let t7 = parseFloat($w( ‘#trainTags7’ ).value); //“What type of workout?”
let t8 = parseFloat($w( ‘#trainTags8’ ).value); //“How intense is the workout?”
let t9 = parseFloat($w( ‘#trainTags9’ ).value); //“What is the duration of each workout?”
let t10 = parseFloat($w( ‘#trainTags10’ ).value); //“How often do you workout?”
if (t6 === 0 ) {
t7 = 0 ;
t8 = 0 ;
t9 = 0 ;
t10 = 0 ;
}
let tm1 = parseFloat(t1 + t2 + t3 + t4 + t5 + t6 + t7 + t8 + t9 + t10); //sum of all trainscores
let ts1 = parseFloat((tm1 / 30 ) * 100 ).toFixed( 1 );
let a1 = parseFloat($w( ‘#alcoholTags1’ ).value); //“Do you drink alcohol?”
let a2 = parseFloat($w( ‘#alcoholTags2’ ).value); //“What type of alcohol?”
let a3 = parseFloat($w( ‘#alcoholTags3’ ).value); //“How many drinks per session?”"
let a4 = parseFloat($w( ‘#alcoholTags4’ ).value); //“How often do you drink alcohol?”
if (a1 === 3 ) {
a2 = 3 ;
a3 = 3 ;
a4 = 3 ;
}
let am1 = parseFloat(a1 + a2 + a3 + a4); //sum of all alcoholscores
let as1 = parseFloat((am1 / 12 ) * 100 ).toFixed( 1 );
let f1 = parseFloat($w( ‘#foodTags1’ ).value); //“How is your food in general?”
let f2 = parseFloat($w( ‘#foodTags2’ ).value); //“What type of food do you eat?”
let f3 = parseFloat($w( ‘#foodTags3’ ).value); //“How big are your regular meals?”
let f4 = parseFloat($w( ‘#foodTags4’ ).value); //“How many vegetables per day?”
let f5 = parseFloat($w( ‘#foodTags5’ ).value); //“How many fruits per day?”
let f6 = parseFloat($w( ‘#foodTags6’ ).value); //“How much fish per week?”
let f7 = parseFloat($w( ‘#foodTags7’ ).value); //“How much red meat per week?”
let f8 = parseFloat($w( ‘#foodTags8’ ).value); //“How often do you eat junkfood?”
let f9 = parseFloat($w( ‘#foodTags9’ ).value); //“How often do you eat deep fried?”
let fm1 = parseFloat(f1 + f2 + f3 + f4 + f5 + f6 + f7 + f8 + f9); //sum of all foodscores
let fs1 = parseFloat((fm1 / 27 ) * 100 ).toFixed( 1 );
let b1 = parseFloat($w( ‘#bodyTags1’ ).value); //“How is your health?”
let b2 = parseFloat($w( ‘#bodyTags2’ ).value); //“How many medication pills per day?”
let b3 = parseFloat($w( ‘#bodyTags3’ ).value); //“How many diseases?”
let b4 = parseFloat($w( ‘#bodyTags4’ ).value); //“Do you suffer from infections?”
let b5 = parseFloat($w( ‘#bodyTags5’ ).value); //“How often do you feel lethargic?”
let bm1 = parseFloat(b1 + b2 + b3 + b4 + b5); //sum of all bodyscores
let bs1 = parseFloat((bm1 / 15 ) * 100 ).toFixed( 1 );
$w( “#elysiumDataPsi” ).setFieldValues({
“userName” : userName, //User information
“userEmail” : userEmail,
“userAge” : userAge,
“userAddress” : userAddress,
“userSex” : userSex,
“mindTags1” : m1,
“mindTags2” : m2,
“mindTags3” : m3,
“mindTags4” : m4,
“mindTags5” : m5,
“mindTags6” : m6,
“mindTags7” : m7,
“mindTags8” : m8,
“mindTags9” : m9,
“mindScore” : ms1, //Percentage of max mindscore 99
“smokeTags1” : s1,
“smokeTags2” : s2,
“smokeTags3” : s3,
“smokeTags4” : s4,
“smokeScore” : ss1, //Percentage of max smokescore 120
“trainTags1” : t1,
“trainTags2” : t2,
“trainTags3” : t3,
“trainTags4” : t4,
“trainTags5” : t5,
“trainTags6” : t6,
“trainTags7” : t7,
“trainTags8” : t8,
“trainTags9” : t9,
“trainTags10” : t10,
“trainScore” : ts1, //Percentage of max trainscore 210
“alcoholTags1” : a1,
“alcoholTags2” : a2,
“alcoholTags3” : a3,
“alcoholTags4” : a4,
“alcoholScore” : as1, //Percentage of max mindscore 24
“foodTags1” : f1,
“foodTags2” : f2,
“foodTags3” : f3,
“foodTags4” : f4,
“foodTags5” : f5,
“foodTags6” : f6,
“foodTags7” : f7,
“foodTags8” : f8,
“foodTags9” : f9,
“foodScore” : fs1, //Percentage of max foodscore 27
“bodyTags1” : b1,
“bodyTags2” : b2,
“bodyTags3” : b3,
“bodyTags4” : b4,
“bodyTags5” : b5,
“bodyScore” : bs1, //Percentage of max bodyscore 30
“cardiovascularDisease” : cd2(cd1, sm1, tm1, mm1, bm1, am1, fm1), //Database from elysiumLife. cd1=cardiovascular disease
“cancer” : 3 , //c1=cancer
“respiratoryDisease” : 23 , //r1=respiratory diseases
“diabetesMellitus” : d1, //d1=diabetes DM type II
“brain” : br1, //br1=brain
“infection” : i1, //i1=infection
“accidents” : ac1, //ac1=accidents
“drugAbuse” : dr1, //dr1=drug abuse
“lifeSpan” : l1, //l1=lifeSpan
“suicide” : su1, //s1=suicide
“bioAge” : l1, //populating projections
“bodyAge” : (l1 * 1.2 ).toFixed( 2 ),
“mentalAge” : l1 * 2.3 ,
“projectedLifespan” : l1 * 1.8 ,
“projectedLifecycle” : l1 - userAge,
“statHealth” : 10 ,
“statPerformance” : 20 ,
“statStress” : 30 ,
“bioDefense” : 40 ,
“height” : 175 , //trying pseudo data
“weight” : 75 ,
“waist” : 90 ,
“hips” : 95 ,
“muscleMass” : 45 ,
“bodyFat” : 30 ,
“saturation” : 99 ,
“hsCrp” : 1.2 ,
“hbA1C” : 42.1
});
})
})
})
});

function cd2(cd1, sm1, tm1, mm1, bm1, am1, fm1){
//function for cardiovascular disease
return parseFloat(cd1 + cd1 * ( 0.20 - sm1 / 30 + 0.15 - tm1 / 100 + 0.11 -
mm1 / 120 + 0.09 - bm1 / 83 + 0.07 - am1 / 85 + 0.05 - fm1 / 270 )).toFixed( 1 );

}

Hello Salman2301,

i have a little trouble to use —> .then(()=>{})-Code

Here my CODE-SNIPET…

export function DDuseritems_change(event) {
 let ttt=$w("#DDuseritems").selectedIndex
 let DatenQuery=wixData.query("SM-Verwaltung")
    .eq("_owner", BenutzerId)
    .find()
    .then((results) => {
 let Gefundeneitems = results.items;
 
        console.log(results)
        console.log(Gefundeneitems)
        console.log(Gefundeneitems.length)

        console.log($w("#DDuseritems").selectedIndex)
        console.log(Gefundeneitems[ttt].title)
        console.log(Gefundeneitems[ttt].server)
        console.log(Gefundeneitems[ttt].reich)
        console.log(Gefundeneitems[ttt].rasse)
        console.log(Gefundeneitems[ttt].itemTyp)
        console.log(Gefundeneitems[ttt].itemStufe)
        console.log(Gefundeneitems[ttt].itemLevel)
        console.log(Gefundeneitems[ttt].itemPreis)
        console.log(Gefundeneitems[ttt].wahrung)
        console.log(Gefundeneitems[ttt].verkaufer)

        console.log($w("#DDbonus1").options)
        console.log(Gefundeneitems[ttt].bonus1)
        console.log(Gefundeneitems[ttt].bonus2)
        console.log(Gefundeneitems[ttt].bonus3)
        console.log(Gefundeneitems[ttt].bonus4)
        console.log(Gefundeneitems[ttt].bonus5)
        console.log(Gefundeneitems[ttt].bonus6)
        console.log(Gefundeneitems[ttt].bonus7)

        console.log(Gefundeneitems[ttt].p1)
        console.log(Gefundeneitems[ttt].p2)
        console.log(Gefundeneitems[ttt].p3)
        console.log(Gefundeneitems[ttt].p4)
        console.log(Gefundeneitems[ttt].p5)
        console.log(Gefundeneitems[ttt].p6)
        console.log(Gefundeneitems[ttt].p7)     

        console.log(Gefundeneitems[ttt].bildUrl)
        console.log("VERWALTUNGS-ID = " + Gefundeneitems[ttt]._id)
        console.log("URSPRUNGS-ID = " + Gefundeneitems[ttt].ursprungsId)
 
        ItemIDverwaltung=Gefundeneitems[ttt]._id
        ItemIDursprung = Gefundeneitems[ttt].ursprungsId,
        Bild = Gefundeneitems[ttt].bildUrl
 
        $w("#DD1").value = Gefundeneitems[ttt].server
        $w("#DD2").value = Gefundeneitems[ttt].reich
        $w("#TXTrasse").value = Gefundeneitems[ttt].rasse
        $w("#TXTitemtyp").value = Gefundeneitems[ttt].itemTyp
        $w("#DD5").value = Gefundeneitems[ttt].itemStufe
        $w("#TXTlevel").value = Gefundeneitems[ttt].itemLevel

        $w("#DDbonus1").value = Gefundeneitems[ttt].bonus1
        $w("#DDbonus2").value = Gefundeneitems[ttt].bonus2
        $w("#DDbonus3").value = Gefundeneitems[ttt].bonus3
        $w("#DDbonus4").value = Gefundeneitems[ttt].bonus4
        $w("#DDbonus5").value = Gefundeneitems[ttt].bonus5
        $w("#DDbonus6").value = Gefundeneitems[ttt].bonus6
        $w("#DDbonus7").value = Gefundeneitems[ttt].bonus7
 
 
        $w("#IMGverwaltung").src = Gefundeneitems[ttt].bildUrl
        $w("#TXTpreis").value = Gefundeneitems[ttt].itemPreis
        $w("#TXTwahrung").value = Gefundeneitems[ttt].wahrung
        $w("#TXTmenge").value = Gefundeneitems[ttt].menge
        $w("#TXTverkaufer").value = Gefundeneitems[ttt].verkaufer
        $w("#TXTauswahl").value = $w("#DDuseritems").selectedIndex+1
        $w("#TXTbox1").value = Gefundeneitems[ttt].nachricht
 
 if($w("#TXTwahrung").value=="Yang"){$w("#SWITCH4").checked=true} else {$w("#SWITCH4").checked=false}
 
 if(Gefundeneitems[ttt].itemTyp=="Waffe") {start_Befüllung_Bonus1_5 ("Waffen")}
 else if(Gefundeneitems[ttt].itemTyp=="Rüstung") {start_Befüllung_Bonus1_5 ("Rüstungen")}
 else if(Gefundeneitems[ttt].itemTyp=="Helm") {start_Befüllung_Bonus1_5 ("Helme")}
 else if(Gefundeneitems[ttt].itemTyp=="Schild") {start_Befüllung_Bonus1_5 ("Schilder")}
 else if(Gefundeneitems[ttt].itemTyp=="Waffe") {start_Befüllung_Bonus1_5 ("Waffen")}
 else if(Gefundeneitems[ttt].itemTyp=="Waffe") {start_Befüllung_Bonus1_5 ("Waffen")}
 
        zzz()
/*  
    .then(()=>{
        $w("#DDprozente1").value = Gefundeneitems[ttt].p1
        $w("#DDprozente2").value = Gefundeneitems[ttt].p2
        $w("#DDprozente3").value = Gefundeneitems[ttt].p3
        $w("#DDprozente4").value = Gefundeneitems[ttt].p4
        $w("#DDprozente5").value = Gefundeneitems[ttt].p5
        $w("#DDprozente6").value = Gefundeneitems[ttt].p6
        $w("#DDprozente7").value = Gefundeneitems[ttt].p7   
    })
*/
        setTimeout(()=>{
            $w("#DDprozente1").value = Gefundeneitems[ttt].p1
            $w("#DDprozente2").value = Gefundeneitems[ttt].p2
            $w("#DDprozente3").value = Gefundeneitems[ttt].p3
            $w("#DDprozente4").value = Gefundeneitems[ttt].p4
            $w("#DDprozente5").value = Gefundeneitems[ttt].p5
            $w("#DDprozente6").value = Gefundeneitems[ttt].p6
            $w("#DDprozente7").value = Gefundeneitems[ttt].p7   
        },750)      
    })      
}


(All console-logs working fine!)

The code works like it is, but i want to eleminate —> the “setTimeout” out of my code and want to use —> .then(()=>… instead of setTimeout-Code.

But when i do that, my code stop working.

I know, that my code has to work sequential.

I want that the red marked CODE-BLOCK runs at the absolutely end of the sequenz/code (after the function ----> zzz() ).

How can i realize it with —> .then()=>…

Thanks for HELP and EXPLANATION

can u share the zzz()

zzz()

If the function has somesort promise(when u use wixData.query or any other serverCall)
The promise will be run after the function “DDuseritems_change” excuted
that’s how Javascript works

You can return promise from zzz function
and than use .then to run the code after the zzz is resolved

Hello again, yes of course… here it is …

function zzz(){
 for (var i = 1; i <= 5; i++) {
        start_BonusAutofill (i)
    }
}
function start_BonusAutofill (parameter) {
 // Autofill-Abfrage
 let Auswahl_Bonus = $w('#DDbonus'+parameter)
 let Auswahl_Prozente = $w('#DDprozente'+parameter)
    console.log(Auswahl_Bonus)
        $w('#DDprozente'+parameter).value=""

 if (Auswahl_Bonus.value=="Abwehr gg. Verlangsamung" || Auswahl_Bonus.value=="Abwehr gg. Ohnmacht"  || Auswahl_Bonus.value=="+DMG bei niedrigen Rangpunkten") {Auswahl_Prozente.disable()}

 else if (Auswahl_Bonus.value=="Nahkampftreffer-Reflektieren" || Auswahl_Bonus.value=="Nahkampftreffer Abblocken" || 
        Auswahl_Bonus.value=="Schwertverteidigung" || Auswahl_Bonus.value=="Zweihandverteidigung" || Auswahl_Bonus.value=="Glockenverteidigung"  || Auswahl_Bonus.value=="Dolchverteidigung" || Auswahl_Bonus.value=="Fächerverteidigung" || Auswahl_Bonus.value=="Krallenverteidigung" || Auswahl_Bonus.value=="Pfeilwiderstand" ||
        Auswahl_Bonus.value=="Magiewiderstand" || Auswahl_Bonus.value=="Blitzwiderstand" || Auswahl_Bonus.value=="Feuerwiderstand" || Auswahl_Bonus.value=="Windwiderstand" || Auswahl_Bonus.value=="Erdwiderstand" || Auswahl_Bonus.value=="Widerstand gg. Dunkelheit" || Auswahl_Bonus.value=="Chance Pfeilangriffen auszuweichen" ||
        Auswahl_Bonus.value=="Bewegungsgeschwindigkeit") {
        Auswahl_Prozente.options = [
            {"label": "", "value": ""},
            {"label": "25%", "value": "25%"},
            {"label": "20%", "value": "20%"},
            {"label": "16%", "value": "16%"},
            {"label": "15%", "value": "15%"},
            {"label": "14%", "value": "14%"},
            {"label": "13%", "value": "13%"},
            {"label": "12%", "value": "12%"},
            {"label": "11%", "value": "11%"},
            {"label": "10%", "value": "10%"},
            {"label": "9%", "value": "9%"},
            {"label": "8%", "value": "8%"},
            {"label": "7%", "value": "7%"},
            {"label": "6%", "value": "6%"},
            {"label": "5%", "value": "5%"},
            {"label": "4%", "value": "4%"},
            {"label": "3%", "value": "3%"},
            {"label": "2%", "value": "2%"},
            {"label": "1%", "value": "1%"}
        ]
    }

 else if (Auswahl_Bonus.value=="EXP-Bonus" || Auswahl_Bonus.value=="Yang-Bonus" || Auswahl_Bonus.value=="Zaubergeschwindigkeit" ||
    Auswahl_Bonus.value=="Stark gg. Teufel" || Auswahl_Bonus.value=="Stark gg. Untote" || Auswahl_Bonus.value=="Stark gg. Tiere" || Auswahl_Bonus.value=="Stark gg. Orks" || Auswahl_Bonus.value=="Stark gg. Esoterische" || Auswahl_Bonus.value=="Bewegungsgeschwindigkeit" || Auswahl_Bonus.value=="Doppelte Menge Gegenstand") {
        Auswahl_Prozente.options = [
            {"label": "", "value": ""},
            {"label": "20%", "value": "20%"},
            {"label": "19%", "value": "19%"},
            {"label": "18%", "value": "18%"},
            {"label": "17%", "value": "17%"},
            {"label": "16%", "value": "16%"},
            {"label": "15%", "value": "15%"},
            {"label": "14%", "value": "14%"},
            {"label": "13%", "value": "13%"},
            {"label": "12%", "value": "12%"},
            {"label": "11%", "value": "11%"},
            {"label": "10%", "value": "10%"},
            {"label": "9%", "value": "9%"},
            {"label": "8%", "value": "8%"},
            {"label": "7%", "value": "7%"},
            {"label": "6%", "value": "6%"},
            {"label": "5%", "value": "5%"},
            {"label": "4%", "value": "4%"},
            {"label": "3%", "value": "3%"},
            {"label": "2%", "value": "2%"},
            {"label": "1%", "value": "1%"}
        ]
 .
 .
 .
 some.....more.....code....here...of...same...type
 .
 .
 .
 .

 // Alchemie-Bonis-------------------------------------------------------------------------------------------------------------------Alchemie
 else if (Auswahl_Bonus.value=="Magieangriff" || Auswahl_Bonus.value=="Magieverteidigung" || Auswahl_Bonus.value=="Stärke (STR)" || Auswahl_Bonus.value=="Vitalität (VIT)" || Auswahl_Bonus.value=="Beweglichkeit (DEX)" || Auswahl_Bonus.value=="Intelligenz (INT)"){
        Auswahl_Prozente.options = [
            {"label": "+24", "value": "+24"},
            {"label": "+21", "value": "+21"},
            {"label": "+18", "value": "+18"},
            {"label": "+16", "value": "+16"},
            {"label": "+15", "value": "+15"},
            {"label": "+14", "value": "+14"},
            {"label": "+13", "value": "+13"},
            {"label": "+12", "value": "+12"},
            {"label": "+11", "value": "+11"},
            {"label": "+10", "value": "+10"},
            {"label": "+9", "value": "+9"},
            {"label": "+8", "value": "+8"},
            {"label": "+7", "value": "+7"},
            {"label": "+6", "value": "+6"},
            {"label": "+5", "value": "+5"},
            {"label": "+4", "value": "+4"},
            {"label": "+3", "value": "+3"},
            {"label": "+2", "value": "+2"},
            {"label": "+1", "value": "+1"},

        ]
    }
 else{console.log("ffffffffffffffffffffffffffffffffff")}
}

here the link to the original page… so you can see how it looks like…

https://mt2-king.wixsite.com/website/sm-benutzerkonto


Ok, big THANKS goes to SALMAN!!!
I could find a better solution where i can do my CODE without ----> setTimeOut(()=>…

Now it looks like that and works fine for me…

export function DDuseritems_change(event) {
 let ttt=$w("#DDuseritems").selectedIndex
 let DatenQuery=wixData.query("SM-Verwaltung")
    .eq("_owner", BenutzerId)
    .find()
    .then((results) => {
        Gefundeneitems = results.items;

        ItemIDverwaltung=Gefundeneitems[ttt]._id
        ItemIDursprung = Gefundeneitems[ttt].ursprungsId,
        Bild = Gefundeneitems[ttt].bildUrl
 
        $w("#DD1").value = Gefundeneitems[ttt].server
        $w("#DD2").value = Gefundeneitems[ttt].reich
        $w("#TXTrasse").value = Gefundeneitems[ttt].rasse
        $w("#TXTitemtyp").value = Gefundeneitems[ttt].itemTyp
        $w("#DD5").value = Gefundeneitems[ttt].itemStufe
        $w("#TXTlevel").value = Gefundeneitems[ttt].itemLevel

        $w("#DDbonus1").value = Gefundeneitems[ttt].bonus1
        $w("#DDbonus2").value = Gefundeneitems[ttt].bonus2
        $w("#DDbonus3").value = Gefundeneitems[ttt].bonus3
        $w("#DDbonus4").value = Gefundeneitems[ttt].bonus4
        $w("#DDbonus5").value = Gefundeneitems[ttt].bonus5
        $w("#DDbonus6").value = Gefundeneitems[ttt].bonus6
        $w("#DDbonus7").value = Gefundeneitems[ttt].bonus7
 
 
        $w("#IMGverwaltung").src = Gefundeneitems[ttt].bildUrl
        $w("#TXTpreis").value = Gefundeneitems[ttt].itemPreis
        $w("#TXTwahrung").value = Gefundeneitems[ttt].wahrung
        $w("#TXTmenge").value = Gefundeneitems[ttt].menge
        $w("#TXTverkaufer").value = Gefundeneitems[ttt].verkaufer
        $w("#TXTauswahl").value = $w("#DDuseritems").selectedIndex+1
        $w("#TXTbox1").value = Gefundeneitems[ttt].nachricht
 
 if($w("#TXTwahrung").value=="Yang"){$w("#SWITCH4").checked=true} else {$w("#SWITCH4").checked=false}
 
 if(Gefundeneitems[ttt].itemTyp=="Waffe") {start_Befüllung_Bonus1_5 ("Waffen")}
 else if(Gefundeneitems[ttt].itemTyp=="Rüstung") {start_Befüllung_Bonus1_5 ("Rüstungen")}
 else if(Gefundeneitems[ttt].itemTyp=="Helm") {start_Befüllung_Bonus1_5 ("Helme")}
 else if(Gefundeneitems[ttt].itemTyp=="Schild") {start_Befüllung_Bonus1_5 ("Schilder")}
 else if(Gefundeneitems[ttt].itemTyp=="Waffe") {start_Befüllung_Bonus1_5 ("Waffen")}
 else if(Gefundeneitems[ttt].itemTyp=="Waffe") {start_Befüllung_Bonus1_5 ("Waffen")}
 
        zzz()
/*
        setTimeout(()=>{
            $w("#DDprozente1").value = Gefundeneitems[ttt].p1
            $w("#DDprozente2").value = Gefundeneitems[ttt].p2
            $w("#DDprozente3").value = Gefundeneitems[ttt].p3
            $w("#DDprozente4").value = Gefundeneitems[ttt].p4
            $w("#DDprozente5").value = Gefundeneitems[ttt].p5
            $w("#DDprozente6").value = Gefundeneitems[ttt].p6
            $w("#DDprozente7").value = Gefundeneitems[ttt].p7   
        },750)  
*/ 
    })  
        .then(()=>{
            $w("#DDprozente1").value = Gefundeneitems[ttt].p1
            $w("#DDprozente2").value = Gefundeneitems[ttt].p2
            $w("#DDprozente3").value = Gefundeneitems[ttt].p3
            $w("#DDprozente4").value = Gefundeneitems[ttt].p4
            $w("#DDprozente5").value = Gefundeneitems[ttt].p5
            $w("#DDprozente6").value = Gefundeneitems[ttt].p6
            $w("#DDprozente7").value = Gefundeneitems[ttt].p7   
        })  
}


function zzz(){
 for (var i = 1; i <= 5; i++) {
        start_BonusAutofill (i)
    }
}

Thanks for your advise. Perhaps it is still not the best solution, but it works quick and stable.:grin:

@Salman2301 Do you have some tips and tricks on how to tackle this?

99% sure this should be asked here (says everyone immediately before they post something which absolutely does not belong here). I’m making a website for an assignment submission at uni, won’t bore you with the specifics, but I did most of it in the normal website editor. The one issue was adding a home button on all the pages other than the home page (obviously) and since I’m the personification of lazy I decided to set the element/button to appear on all pages and then use the code window/console to set it not to appear on the home page. I got the code from one of the tutorial web pages for Corvid and it said to copy lines 3 and 4 into the console thing on the page you want the element not to appear on.

$w.onReady(function () {
 //TODO: write your page related code here...
// Hides the element when the page loads
$w("#button6").hide();
});

The reason I think my question goes here is that it actually seems to work sometimes, other times it seems to just not work at all and sometimes it works at first (not on homepage, then appears on another page but once you click on it to return to the home page it then disappears everywhere else).
I published the site if it helps https://trr030.wixsite.com/tbdcompany
Note that on the homepage the picture is set as links to the various parts of the pages (i just haven’t put any text on them yet)
I doubt I failed at copy and pasting text from one place to another so is it a case of the code is only meant for static elements?
My apologies to anyone shaking their head after reading this far :sweat_smile:
I should also apologise for how quickly this became an essay

I was doing some thinking if I added the same code to every other page except instead of “hide” made it “show” would that solve the problem?

You need to add the code in site section
You can read more about different type of code panel here
https://support.wix.com/en/article/corvid-working-in-the-code-panel

Closing the thread
hope this was useful,
We(Corvid master) will do Code review on every Friday ,
get ready for the next code review on JUNE, 12th 2020
Happy coding :v: