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

July 24th, 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 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 an explanation of what the code does is useful!
Marked * are required

Don’ts

1: Do NOT include any sensitive code (like passwords, secret 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)

Comment not related to refactoring for the code will be get deleted to organize

Notes

  • We do code review every Friday PST timezone!

  • This post will be locked after 24 hours (today post will be till PST 9am)

Hello, i know it’s a late post, but it is still friday :grin:.

It is also more simple this time.

I have 2 databases (Courses) & (Instructors).
The (Courses)-DATABASE is connected to a DYNAMIC-PAGE and contains several references with items (courses) + instructor-names of the current courses.

The second DATABASE (Instructors) contains all availible instructors.

Now my situation & aim:

  • I want to get the INDEX-NUMBER of the current selected course on the DYNAMIC-PAGE, stored in DATABASE (Instructor).

So here is the CODE:

import wixData from "wix-data";

var INDEX

$w.onReady(function () {
    $w("#dynamicDataset").onReady( () => {
         function1()  
    });
});

//Get DATA of the current selected item.
function function1 (parameter) {
 let Courses = $w("#dynamicDataset").getCurrentItem();
    console.log(Courses)
//  console.log(Courses.instructorName)
//  console.log(Courses.instructorName.title)
    function2 (Courses.instructorName.title)
}


// Find the current Instructor (current DATA-ROW)
function function2 (parameter) {
    console.log(parameter)
    wixData.query("Instructors")
//  .eq('title', parameter)
    .find()
    .then( (results) => {
 if(results.items.length > 0) {
 let firstItem = results.items[0];
            console.log(results)
            console.log(firstItem)

 for (let i = 0; i < results.items.length; i++ ) {
                    console.log(results.items[i].title)
 
 if (results.items[i].title == parameter) {  
                    INDEX = i
                    console.log("TheIndex found is " + INDEX )
                }
            }   
        } 
 else {      }
    })
    .catch( (err) => {
 let errorMsg = err;
    });
}

// Save QUOTE-DATA
function function3 (parameter) {
    $w("#dynamicDataset").onReady( () => {
        $w("#dataset5").setCurrentItemIndex(INDEX)
        .then(()=>{
            console.log($w('#dataset5').getCurrentItem())
            $w("#dataset5").setFieldValue("quote", $w('#iptQuote').value);
            $w("#dataset5").save();
        })
    })
}

export function BTNsetQuote_click(event) {function3()}

Here you can see, the following process…

  1. get the currentItem of the current selected DynamicPage.
  2. search for the common denominator of this two databases (in this case → the NAME/TITLE)
  3. Query DATABASE-B (INSTRUCTOR) .
  4. Search for the current selected INDEX.
  5. Set the founded INDEX on DATABASE-B
  6. And save he item with some value.

You can see an example here…
https://russian-dima.wixsite.com/meinewebsite/dynamic-action

My question is: Isn’t there a much faster and better way, then this one?

I have several buttons I use to switch between states in a multi-state box on the following webpage:
https://www.rainforestartproject.org/newconnections

When one is clicked, it changes the state, shows a hidden button for the state that is active, and hides the buttons for the non-active states.

The code I have is below. It all works great, but it seems like it could be shortened somehow?

$w.onReady(function () {
    $w("#buttonG1").onClick(() => {
        $w('#programSummaryBox').changeState("grade1");
        $w('#buttonGkhid, #buttonG2hid, #buttonG3hid, #buttonG4hid, #buttonG5hid').hide();
        $w('#buttonG1hid').show();
 
    })
})

$w.onReady(function () {
    $w("#buttonG2").onClick(() => {
        $w('#programSummaryBox').changeState("grade2");
        $w('#buttonGkhid, #buttonG1hid, #buttonG3hid, #buttonG4hid, #buttonG5hid').hide();
        $w('#buttonG2hid').show();
    })
})

$w.onReady(function () {
    $w("#buttonG3").onClick(() => {
        $w('#programSummaryBox').changeState("grade3");
        $w('#buttonGkhid, #buttonG1hid, #buttonG2hid, #buttonG4hid, #buttonG5hid').hide();
        $w('#buttonG3hid').show();
    })
})

$w.onReady(function () {
    $w("#buttonG4").onClick(() => {
        $w('#programSummaryBox').changeState("grade4");
        $w('#buttonGkhid, #buttonG1hid, #buttonG2hid, #buttonG3hid, #buttonG5hid').hide();
        $w('#buttonG4hid').show();
    })
})

$w.onReady(function () {
    $w("#buttonG5").onClick(() => {
        $w('#programSummaryBox').changeState("grade5");
        $w('#buttonGkhid, #buttonG1hid, #buttonG2hid, #buttonG3hid, #buttonG4hid').hide();
        $w('#buttonG5hid').show();
    })
})

$w.onReady(function () {
    $w("#buttonGk").onClick(() => {
        $w('#programSummaryBox').changeState("gradeK");
        $w('#buttonG1hid, #buttonG2hid, #buttonG3hid, #buttonG4hid, #buttonG5hid').hide();
        $w('#buttonGkhid').show();
    })
})

I have a page with a database named #ncGrade2Data which has a field named " extension" which is an image gallery. If there are no images in that field, I want the strip that contains the gallery to collapse.

The code below works to do this, but in Preview mode I receive this error:

Like I said, the code works, so I’m wondering what the error means / do I need to fix anything?

import wixData from 'wix-data';

$w.onReady(function () {
    $w("#ncGrade2Data").onReady(() => {
 var item = $w("#ncGrade2Data").getCurrentItem();
 if (item["extension"] === undefined) $w("#extensionStrip").collapse();
 else $w("#extensionStrip").expand();
    });
});

There is two way to do it
I prefer the wixData.update
as it feels reliable


// SOLUTION 1:
/*
 We can get the Instructor details from the dynamic dataset and 
 Update the collection from wixData update 

 If you wanna update to different database you will need to query the database
 to get the _id before update the value
*/ 
import wixData from "wix-data";


$w.onReady(function () {
  $w("#dynamicDataset").onReady(() => {
    $w("#dataset5").onReady(() => {
      saveQuoteData();
    });
  });
});

async function saveQuoteData() {
 const courses = $w("#dynamicDataset").getCurrentItem();
 
 const instructor = courses.instructorName;
 const instructorName = instructor.title;

  instructor.quote = $w('#iptQuote').value;
  wixData.update("Instructors", instructor)
  .then((updated)=>{
    console.log("Updated the 'Instructors' database :", updated);
  })
  .catch(console.error)

}

// SOLUTION 2:
/*
  Filter the dataset and use setFieldvalue and Save to update the quote on page load
  You can also call the saveQuoteData function on a button click
*/
import wixData from "wix-data";


$w.onReady(function () {
  $w("#dynamicDataset").onReady(() => {
    $w("#dataset5").onReady(() => {
      saveQuoteData();
    });
  });
});



async function saveQuoteData() {
 const courses = $w("#dynamicDataset").getCurrentItem();
 const instructorName = courses.instructorName.title;

 const filter = wixData.filter().eq("title", instructorName);
 await $w("#dataset5").setFilter(filter); // filtering the dataset will update the current Index
  console.log("Updating Quote")
 await $w("#dataset5").setFieldValue("quote", $w('#iptQuote').value);
 await $w("#dataset5").save();

}


And thank you for the continue support I appreciate it.
I was busy for comming weeks due to client works
Will try my best to be on time next time
Feel free to shoot me a message @russian

This is a great example why i initiated the code review
Yes we can improve it
Here is the following code

We store all the button element ID in an Array
and there is another variable which store a key value
so the button ID is map to stateID of the lightbox

buttonID <=> stateID

then we can loop throw all the button
add the onclick event
and change the state (We get the state id from the multiState variable)
and hide all the button and show the current btn with the id


const btnEl = [
 "buttonGk",
 "buttonG1",
 "buttonG2",
 "buttonG3",
 "buttonG4",
 "buttonG5"
]

const multiState = {
  buttonG1: "grade1",
  buttonG2: "grade2",
  buttonG3: "grade3",
  buttonG4: "grade4",
  buttonG5: "grade5",
  buttonGk: "gradeK",
}

$w.onReady(function () {
  btnEl.forEach(btnID => {
    $w("#" + btnID).onClick(() => {
        $w('#programSummaryBox').changeState(multiState[btnID]);
 const notClickedBtn = currBtnID => currBtnID !==  btnID;
        $w('#' + btnEl.filter(notClickedBtn).join("hid, #") ).hide();
        $w(`#${btnID}hid`).show();
    })
  });
});

looks like WIX bug
try to contact support
and IMO it should fix on it;s own
if not create a new page and test the code
and see if it still throw the error
Try to uncomment the error and see the error still exist
If you want to help the support to fix the bug faster

Big thanks like always! No Problem ^^ i will wait for nxt itme (preparing new content) ^^