Code Review Friday: (Let's Improve your code, ask Corvid Master)

May 15th, 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!

  • This post will be locked after 24 hours

Hi,
I would like some input on my code. Its a quiz slideshow by using seletiontags and only single-tags.
// For full API documentation, including code examples, visit Velo API Reference - Wix.com
$w.onReady( function () {
//TODO: write your page related code here…
//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 = ;
}
selectedTags.onChange((event) => {
if (!event.target.value || event.target.value.length === 0 ) {
event.target.value = [prevSelectedValue];
} else {
event.target.value = event.target.value.filter(x => x !== prevSelectedValue);
prevSelectedValue = event.target.value[ 0 ];
}
//Change slides on selection
$w( ‘#quizSlides’ ).next();
})
//skip slides on smoking if answer no
$w( ‘#Smoke1’ ).onChange((event)=> {
$w( ‘#Smoke1’ ).value.forEach(tag =>{
if (tag=== ‘No’ ){
$w( ‘#quizSlides’ ).changeSlide( 13 );
}
})
})
//Skip slides on training if answer no

//Skip slides on alcohol if answer is no

}) 

});

In addition, I would really love to hide slides 10, 11 and 12 if the answer on slide 9 “do you smoke” is “No”.
Please have a look: https://www.nordicelysium.com/blank

Thanks!

Hello @peter tran

I personally like your clever code

you can get the current element id from the target object
and based on the selection id and prevSelected value
we can write a condition either to skip or show next slide
Let me know if you have question

See the changes code for quick understanding of the logic

Full code


$w.onReady(function () {
 //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 = [];
    }
 
    selectedTags.onChange((event) => {
 if (!event.target.value || event.target.value.length === 0) {
        event.target.value = [prevSelectedValue];
      } else {
        event.target.value = event.target.value.filter(x => x !== prevSelectedValue);
        prevSelectedValue = event.target.value[0];
      }
 //Change slides on selection
 
 const currTagId = event.target.id;
 
      console.log({currTagId, prevSelectedValue}); // remove this after working

 if(currTagId=== "Smoke1") {
 if(prevSelectedValue === "No") {
          console.log("skip slided to 13")
          $w('#quizSlides').changeSlide(13);
        } else {
          $w('#quizSlides').next();
        }
      } else {
        $w('#quizSlides').next();
      }
    });


 // //skip slides on smoking if answer no

 //Skip slides on training if answer no

 //Skip slides on alcohol if answer is no

  })
});

Changes :-


 const currTagId = event.target.id;
 
      console.log({currTagId, prevSelectedValue}); // remove this after working

 if(currTagId=== "Smoke1") {
 if(prevSelectedValue === "No") {
          console.log("skip slided to 13")
          $w('#quizSlides').changeSlide(13);
        } else {
          $w('#quizSlides').next();
        }
      } else {
        $w('#quizSlides').next();
      }
}

I am using code below (staright out of wix) in a grouped ratings input. It works sometimes after repeating the input twice and does not other times? Can you help?

===
import wixLocation from ‘wix-location’;
import wixData from “wix-data”;
import { local } from ‘wix-storage’;

$w.onReady( function () {
//TODO: write your page related code here…
});

export function RatingsInput1_change(event) {
$w(’ #dynamicDataset ').onReady(() => { const currentItem = $w(" #dynamicDataset ").getCurrentItem();

const average = currentItem.alphaAvg;
const count = currentItem.alpha;
const total = currentItem.alphaTotal;

const newRating = $w(’ #ratingsInput1 ').value;

const newAverageLong = (total + newRating) / (count + 1);
const newAverageShort = Number.parseFloat(newAverageLong).toFixed(1);

  $w(' [#dynamicDataset](https://www.wix.com/corvid/forum/search/~num~dynamicDataset) ').setFieldValues({ 
    'alphaAvg': newAverageShort, 
    'alphaTotal': total + newRating, 
    'alpha': (count + 1) 
  }); 

  $w(' [#dynamicDataset](https://www.wix.com/corvid/forum/search/~num~dynamicDataset) ').save() 
    . catch ((err) => { 
      console.log('could not save new rating'); 
    }); 
}); 

}

export function ratingsInput2_change(event) {
$w(" #dynamicDataset ").onReady(() => {

const currentItem = $w(" #dynamicDataset ").getCurrentItem();

const average = currentItem.bravoAvg;
const count = currentItem.bravo;
const total = currentItem.bravoTotal;

const newRating = $w(’ #ratingsInput2 ').value;
const newAverageLong = (total + newRating) / (count + 1);

const newAverageShort = Number.parseFloat(newAverageLong).toFixed(1);

  $w(' [#dynamicDataset](https://www.wix.com/corvid/forum/search/~num~dynamicDataset) ').setFieldValues({ 
    'bravoAvg': newAverageShort, 
    'bravoTotal': total + newRating, 
    'bravo': (count + 1) 
  }); 

  // save the dataset fields to the collection 
  $w(' [#dynamicDataset](https://www.wix.com/corvid/forum/search/~num~dynamicDataset) ').save() 
    . catch ((err) => { 
      console.log('could not save new rating'); 
    }); 
}); 

}

export function ratingsInput3_change(event) {
$w(" #dynamicDataset “).onReady(() => {
// get the current item from the dataset
const currentItem = $w(” #dynamicDataset ").getCurrentItem();

const average = currentItem.charlieAvg;
const count = currentItem.charlie;
const total = currentItem.charlieTotal;

const newRating = $w(’ #ratingsInput3 ').value;

const newAverageLong = (total + newRating) / (count + 1);
const newAverageShort = Number.parseFloat(newAverageLong).toFixed(1);

  $w(' [#dynamicDataset](https://www.wix.com/corvid/forum/search/~num~dynamicDataset) ').setFieldValues({ 
    'charlieAvg': newAverageShort, 
    'charlieTotal': total + newRating, 
    'charlie': (count + 1) 
  }); 

  // save the dataset fields to the collection 
  $w(' [#dynamicDataset](https://www.wix.com/corvid/forum/search/~num~dynamicDataset) ').save() 
    . catch ((err) => { 
      console.log('could not save new rating'); 
    }); 
}); 

}

export function ratingsInput4_change(event) {
$w(" #dynamicDataset ").onReady(() => {

const currentItem = $w(" #dynamicDataset ").getCurrentItem();

const average = currentItem.deltaAvg;
const count = currentItem.delta;
const total = currentItem.deltaTotal;

const newRating = $w(’ #ratingsInput4 ').value;

const newAverageLong = (total + newRating) / (count + 1);
const newAverageShort = Number.parseFloat(newAverageLong).toFixed(1);

  $w(' [#dynamicDataset](https://www.wix.com/corvid/forum/search/~num~dynamicDataset) ').setFieldValues({ 
    'deltaAvg': newAverageShort, 
    'deltaTotal': total + newRating, 
    'delta': (count + 1) 
  }); 

  // save the dataset fields to the collection 
  $w(' [#dynamicDataset](https://www.wix.com/corvid/forum/search/~num~dynamicDataset) ').save() 
    . catch ((err) => { 
      console.log('could not save new rating'); 
    }); 
}); 

}

export function ratingsInput5_change(event) {
$w(’ #dynamicDataset ').onReady(() => {

const currentItem = $w(" #dynamicDataset ").getCurrentItem();

const average = currentItem.echoAvg;
const count = currentItem.echo;
const total = currentItem.echoTotal;

const newRating = $w(’ #ratingsInput5 ').value;

const newAverageLong = (total + newRating) / (count + 1);
const newAverageShort = Number.parseFloat(newAverageLong).toFixed(1);

  $w(' [#dynamicDataset](https://www.wix.com/corvid/forum/search/~num~dynamicDataset) ').setFieldValues({ 
    'echoAvg': newAverageShort, 
    'echoTotal': total + newRating, 
    'echo': (count + 1) 
  }); 

  $w(' [#dynamicDataset](https://www.wix.com/corvid/forum/search/~num~dynamicDataset) ').save() 
    . catch ((err) => { 
      console.log('could not save new rating'); 
    }); 
}); 

}

export function ratingsInput6_change(event) {
$w(" #dynamicDataset ").onReady(() => {

const currentItem = $w(" #dynamicDataset ").getCurrentItem();

const average = currentItem.fancyAvg;
const count = currentItem.fancy;
const total = currentItem.fancyTotal;

const newRating = $w(’ #ratingsInput6 ').value;

const newAverageLong = (total + newRating) / (count + 1);
const newAverageShort = Number.parseFloat(newAverageLong).toFixed(1);

  $w(' [#dynamicDataset](https://www.wix.com/corvid/forum/search/~num~dynamicDataset) ').setFieldValues({ 
    'fancyAvg': newAverageShort, 
    'fancyTotal': total + newRating, 
    'fancy': (count + 1) 
  }); 

  $w(' [#dynamicDataset](https://www.wix.com/corvid/forum/search/~num~dynamicDataset) ').save() 
    . catch ((err) => { 
      console.log('could not save new rating'); 
    }); 
}); 

}

@salman-hammed
Thanks for the input. I really appreciate it - really nice with the incorporation of prevSelectedValue.
The only thing I am concerned about is if people press “No” on “Smoke1” and it skips to slide 13 but then they press back and see slide 11, 10 and 9. They can then answer questions on smoking even though they answered “No” to smoking if you are following me.

Hi, I am building a job board in wix that would display jobs from a database, with each job in its own repeater.

My relevant database fields are: PositionTitle, CompanyName, Industry, Description,

On this page, I want to add 2 things. 1) a search that searches through PositionTitle & CompanyName 2) a dropdown filter that sorts through Industry.

Currently, I have a search that works for PositionTitle. I’d like to add CompanyName to this also, so that you can search for either CompanyName or PositionTitle in the search bar. Could you help with this?

My dropdown filter for industry does not work. Could you help with this also?

Here is my code. It also includes code for a job counter & a show more toggle in each repeater.

import wixData from "wix-data";

$w.onReady(function () {
    $w("#dynamicDataset").onReady(() => {
 // SHORT DESC CODE
        $w("#listRepeater").onItemReady(($item, itemData) => {
 const { description } = itemData;

 // on item ready set the desc shorter
            $item("#desc").text = shortText(description);
            $item("#showmore").label = "Show More";

            $item("#showmore").onClick((event) => {
 // toggle short desc.
 if ($item("#showmore").label === "Show More") {
                    $item("#desc").text = description;
                    $item("#showmore").label = "Show Less";
                } else {
                    $item("#desc").text = shortText(description);
                    $item("#showmore").label = "Show More";
                }
            });
        });

 function shortText(text, maxLen = 220) {
 return text.substr(0, maxLen) + "...";
        }
    });

 //  FILTER CODE
    $w("#searc").onKeyPress(() => {
 // keypress event trigger before the dom is rendered
 // setTimeout will wait 40ms before excuting the code in filterDs
        setTimeout(filterDs, 40);
    });
 // Dropdown with all the company name
    $w("#dropdown").onChange(() => {
        filterDs();
    });
});

function filterDs() {
 // inital filter
 let filterBuilder = wixData.filter();

 let keyword = $w("#searc").value;
 let dropdown = $w("#dropdown").value;

 if (keyword) {
        filterBuilder = filterBuilder.contains("positionTitle", keyword);
    }

 if (dropdown) {
        filterBuilder = filterBuilder.eq("Industry", dropdown);
    }
    $w("#dynamicDataset").setFilter(filterBuilder);

}

$w.onReady(function () {
 let count = $w("#dynamicDataset").getTotalCount();
   $w("#text110").text = String(count) + " jobs posted";
})

Here is an image of the page in preview. it is not published yet, but my site is live at www.sabeelnetwork.com

@tranenpeter Yeah you will need to use a custom next and prev button
and check if it’s click and based on the slide and selectionTag you can skip the slide

Hi,

if you want to combine search in several fields so PosititionTitle or CompanyName contains the phrase, you can use or operator.

  filterBuilder = filterBuilder.contains("positionTitle", keyword)
    .or(wixData.filter().contains("positionTitle", keyword));

You can find out more about it in the documentation:
https://www.wix.com/corvid/reference/wix-data.WixDataQuery.html#or

On the second issue, it’s not really clear why it doesn’t work. Code looks correct. I would suggest to try logging the the dropdown value is what you expect.

let dropdown = $w("#dropdown").value;
console.log("Dropdown value: " + dropdown);

You will see the value logged in developer console.

TGIF…
Trying to form a Fetch post based on a curl example

I’m not sure if my header is malformed or if I am doing something else basic wrong here. I have been through it half a dozen times and it “looks right” and I have tried variations on the theme but so far no luc.

working from the API Example for POST https://www.wix.com/corvid/reference/wix-fetch.html

I am seeing a warning:
"["Unhandled rejection TypeError: (intermediate value).catch is not a function

//Freshsales Example Account Post
curl -H "Authorization: Token token=sfg999666t673t7t82" -H "Content-Type: application/json" //-d '{"sales_account":{"name":"Widgetz.io (sample)"} }' -X POST "https://domain.freshsales.io/api/sales_accounts"

data.js

function updateFreshSales(item, context)
{
 console.log('function updateFreshSales' );

 const salesURL = 'https://domain.freshsales.io/api/sales_accounts';

 // The data we are going to send in our request
 let data = {
    sales_account : {
      name:  item.companyName
    }
  };
  data = JSON.stringify(data);

 // The parameters we are going pass to the fetch function
  fetch( salesURL, {
 "method" : "post",
 "headers": {
 "Authorization": "Token token=N-dOp-iQLnotmy_token",
 "Content-Type": "application/json"
      },
 "body": data
  })
  .then( (httpResponse) => {
 if (httpResponse.ok) {
 return httpResponse.json();
    } else {
 return Promise.reject("Fetch did not succeed");
    }
  } )
  .then( (json) => console.log(json.someKey) )
  .catch(err => console.log(err))
}  

export function partnerRequests_afterInsert(item, context) {

  sendEmail(item, context);
  updateFreshSales(item, context); 

}

@salman-hammed Makes sense, thanks again.

Please do not include the secreat key renew the key from the api dashboard

I think you are not updating the data variable

data = JSON.stringify(data)

… edited… api key changed.
data = JSON . stringify ( data );

but still failing. closer though.

thank you salman.

@giedrius-grazevicius The search is working now, thank you! The dropdown still doesn’t work for some reason. Any other suggestions would be really helpful!!

further simplified , still not working , but at least I am no longer malformed.

Fetch did not succeed is something I can work with. :slight_smile:

function updateFreshSales(item, context)
{
  console.log('function updateFreshSales' );

 // Freshsales Example Account Post
 // curl -H "Authorization: Token token=sfg999666t673t7t82" -H "Content-Type: application/json" 
 //-d '{"sales_account":{"name":"Widgetz.io (sample)"} }' -X POST "https://domain.freshsales.io/api/sales_accounts"
 
 // The parameters we are going pass to the fetch function
  fetch( "https://domain.freshsales.io/api/sales_accounts", {
 "method" : "post",
 "headers": {
 "Authorization": "Token token=5BouW1Y32h283xifiRQ_FA",
 "Content-Type": "application/json",
      },
 "body": "name=Wonka"
  })
  .then( (httpResponse) => {
 if (httpResponse.ok) {
 return httpResponse.json();
    } else {
 return Promise.reject("Fetch did not succeed");
    }
  } )
  .then( (json) => console.log( "poop" ) )
  .catch(err => console.log(err))
}

@freddy do you mind formatting your post with code? it will be simpler to read :slight_smile:

Try this code

It thorws 403 for me
cause i think i have the wrong token
It should give status code +200


async function updateFreshSales(item, context) {
 try {

    console.log('function updateFreshSales');

 const salesURL = 'https://domain.freshsales.io/api/sales_accounts';

 // The data we are going to send in our request
 let data = {
      sales_account: {
        name: item.companyName
      }
    };

 const headers = {
 "Authorization": "Token token=N-dOp-iQLnotmy_token",
 "Content-Type": "application/json"
    };
 
 const fetchOptions = {
      method: "post",
      headers: headers,
      body: JSON.stringify(data)
    }
 // The parameters we are going pass to the fetch function
 const httpResponse = await fetch(salesURL, fetchOptions);
    console.log({status:httpResponse.status});
 if (!httpResponse.ok) return Promise.reject("Fetch did not succeed");
 const json = await httpResponse.json();

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

  }
 catch (e) {
    console.log("ERROR : ", e.message);
    console.log("TRACE : ", e.stack);

  }
} 

updateFreshSales({companyName: "name"})

Closing the thread
hope this was useful and thanks for all the inputs
We(Corvid master) will do Code review on every Friday ,
get ready for the next code review on 22nd May
Happy coding :v: