Returning null item for no reason

Hi everyone, I have this problem and I can’t find a solution.

import wixData from ‘wix-data’ ;
const collectionName2 = ‘MyAll2’ ;

$w . onReady ( async function () {

**await**  buildFiltersAndPopulateRepeater (); 
$w ( '#gender' ). onChange ( **async**  () => { 
    if  ( $w ( '#genderDecorBackButton' ). checked  ==  **true** ) 
        $w ( '#genderDecorBackButton' ). checked  =  **false** ; 
    **else** 
        $w ( '#genderDecorBackButton' ). checked  =  **true** ; 
    **await**  buildFiltersAndPopulateRepeater () 
}); 

});

async function buildFiltersAndPopulateRepeater () {
let dataQuery = wixData . query ( collectionName2 );

//dataQuery = dataQuery.hasSome('collection', 'FirstPageProducts1'); 

if  ( $w ( '#gender' ). checked  ==  **true** ) {   
    dataQuery  =  dataQuery . hasSome ( 'gender' ,  'Women' ); 
}  **else**  { 
    dataQuery  =  dataQuery . hasSome ( 'gender' ,  'Men' ); 
} 
initRepeater (); 
$w ( '#productList1' ). data  =  **await**  dataQuery . find (). then (( res ) =>  res.items ); 

}

async function initRepeater () {
try {
$w ( ‘#productList1’ ). onItemReady ( async ( $item , itemData ) => {
if ( itemData.product.discountedPrice == itemData.product.price ) {
$item ( ‘#discountBox2’ ). hide ();
$item ( ‘#discount2’ ). hide ();
} else {
$item ( ‘#discount2’ ). text = String ( 100 - Math . round ( 100 * itemData.product.discountedPrice / itemData.product.price )) + “% off” ;
}
const actualProduct = await wixData . query ( collectionName2 )
. include ( ‘brand’ )
. eq ( ‘product’ , itemData.product._id )
. find ()
. then (( res ) => {
let items = res.items ;
if ( items.length > 0 )
return items [ 0 ];
else
return null ;
});
if ( actualProduct && actualProduct.brand ) {
if ( actualProduct.brand.logoblack . startsWith ( ‘http://’ ) || actualProduct.brand.logoblack . startsWith ( ‘https://’ ) || actualProduct.brand.logoblack . startsWith ( ‘wix:image://’ )) {
$item ( ‘#logo1’ ). src = actualProduct.brand.logoblack ;
}
} else {
console . error ( “Error: Cannot read ‘logoblack’ property from undefined or null object.” );
}
$item ( ‘#colors1’ ). text = itemData.color.length + " colors" ;
if ( itemData.ecoFriendly == true )
$item ( ‘#ecoFriendlySign3’ ). expand ();
if ( itemData.sustainable == true )
$item ( ‘#sustainableSign3’ ). expand ();
});
} catch ( error ) {
console . log ( ‘Error fetching data:’ , error );
}
}

I use the code to query a collection called “MyAll2” and filter the results based on the gender selected by the user. It then populates a repeater element with the filtered data and updates some of the item properties.

The actualProduct variable is created inside the onItemReady event handler for the repeater. It’s used to fetch additional data from the same collection, specifically the brand object, for each item in the repeater. This is achieved by creating a new Wix Data query, including the ‘brand’ reference field, and filtering the results by the product ID of the current item.

The resulting actualProduct object contains the brand object as a property.
If the brand object exists and has a property called “logoblack” that starts with “http://”, “https://”, or “wix:image://”, the image source of an element with the ID “logo1” in the repeater item is set to that value.

The function also checks if the item is eco-friendly or sustainable and expands corresponding elements in the repeater if so.
Overall, the code populates a repeater with filtered data and updates the repeater item properties based on additional data fetched from the same collection.

The problem: If I switch the gender, and switch it back in the initial position for example ( From Women to Men, and back to the Women) The actualProduct which I use to take the brand image is returned null. The actualProduct is giving me the product and using .include(brand) is letting me navigate through the brand item from an another dataset, from where I get the black version of the logo (“logoblack”). This is irelevant, why is this happening. Nothing changes, why is returning a null object.

Here are two ss with before and after I switch:

And this is the browser console:

You have a bad coding-style !!!

Change it !!! —> And you will have less problems !!!

import wixData from 'wix-data';
const collectionName2 = 'MyAll2';

$w.onReady(async()=> {   

    //Step-1:getting filter-data....
    let filteredData = await filterAction();
    //Step-2: ---> feeding repeater ...
    $w('#productList1').data = filteredData;
    //Step-3: reacting when repeater got its data...

    $w('#productList1').onItemReady(async ($item, itemData) => {
        if (itemData.product.discountedPrice == itemData.product.price) {
            $item('#discountBox2').hide();
            $item('#discount2').hide();
        } else {
            $item('#discount2').text = String(100 - Math.round(100 * itemData.product.discountedPrice / itemData.product.price)) + "% off";
        }
        const actualProduct = await wixData.query(collectionName2)
            .include('brand')
            .eq('product', itemData.product._id)
            .find()
            .then((res) => {
                let items = res.items;
                if (items.length > 0)
                    return items[0];
                else
                    return null;
            });
        if (actualProduct && actualProduct.brand) {
            if (actualProduct.brand.logoblack.startsWith('http://') || actualProduct.brand.logoblack.startsWith('https://') || actualProduct.brand.logoblack.startsWith('wix:image://')) {
                $item('#logo1').src = actualProduct.brand.logoblack;
            }
        } else {
            console.error("Error: Cannot read 'logoblack' property from undefined or null object.");
        }
        $item('#colors1').text = itemData.color.length + " colors";
        if (itemData.ecoFriendly == true)
            $item('#ecoFriendlySign3').expand();
        if (itemData.sustainable == true)
            $item('#sustainableSign3').expand();
    });

    //What the hell is productList? Box? Dropdown, apple, banana, a car?
    //DEFINE your element-IDs the right way!!!
    // It is a REPEATER --> then also declare it as a REPEATER inside of your code!!!!
    // ---> repProductList <--- GOOOOOOOOOOOD !!!!!
    
    
    // and again APPLE & BANANAS ????? You know what i mean!!!
    //$w('#gender').onChange(async () => {
    
    $w('#gender').onChange(async () => {
        if ($w('#genderDecorBackButton').checked == true)
            $w('#genderDecorBackButton').checked = false;
        else
            $w('#genderDecorBackButton').checked = true;
        await buildFiltersAndPopulateRepeater()
    });
});

async function filterAction() {
    let dataQuery = wixData.query(collectionName2);
    if ($w('#gender').checked == true) {  
        dataQuery = dataQuery.hasSome('gender', 'Women');
    } else {
        dataQuery = dataQuery.hasSome('gender', 'Men');
    }    
}

Hi, thank you for responding and for your observations!

The code you provide is not really corectly connected (filterAction is not returning anything, and when someone change the gender there is no way to update the informations ex: the logo) It is like one time run.

I truly apreciate your dedication, but if you can come with an different alternative, it would be great.
Thank you.

Try this one…

import wixData from 'wix-data';
const myDatabase = 'MyAll2';


$w.onReady(async()=> {console.log("Page ready...");
    
    $w('#gender').onChange(async() => {
        console.log("Gender-Switch changed!");
        if ($w('#genderDecorBackButton').checked) {$w('#genderDecorBackButton').checked===false}
        else {$w('#genderDecorBackButton').checked===true;}
    
        let dataQuery = wixData.query(myDatabase);

        if ($w('#gender').checked) {console.log("Gender = Women");
            dataQuery = dataQuery.hasSome('gender', 'Women');}
        else {console.log("Gender = Men");
            dataQuery = dataQuery.hasSome('gender', 'Men'); 
        }
   
        dataQuery.find()
        .then((res)=>{console.log("Results: ", res.items);
            let items = res.items;
            $w('#productList1').data =items;
        });        
    });


    $w('#productList1').onItemReady(async ($item, itemData) => {
        let productID = itemData.product._id;
        console.log("Product-ID: ", productID);
        let price = itemData.product.price;
        console.log("Price: ", price);
        let discountedPrice = itemData.product.discountedPrice;
        console.log("Discounted-Price: ", discountedPrice);

        if (discountedPrice===itemData.product.price) {
            $item('#discountBox2, #discount2').hide();}
        else {$item('#discount2').text = String(
            100-Math.round(100*discountedPrice/price)) + "% off";
            //$item('#discountBox2, #discount2').show();
        }

        //const actualProduct = await 
        
        wixData.query(myDatabase)
        .include('brand')
        .eq('product', productID)
        .find()
        .then((res) => {console.log("Results-2: ", res);
            let items = res.items;
            if (items.length > 0) {
                let actualProduct = items[0];
                console.log("Actual-Product: ", actualProduct);
                let logoBack = actualProduct.brand.logoblack;
                console.log("Back-Logo: ", logoBack);

                if (actualProduct && actualProduct.brand) {
                    if (logoBack.startsWith('http://') || logoBack.startsWith('https://') || logoBack.startsWith('wix:image://')) {
                        $item('#logo1').src = logoBack;
                    }
                } 
                else {console.error("Error: Cannot read 'logoblack' property from undefined or null object.");}
            
                $item('#colors1').text = itemData.color.length + " colors";
                if (itemData.ecoFriendly) $item('#ecoFriendlySign3').expand();
                if (itemData.sustainable) $item('#sustainableSign3').expand();
            }           
        });       
    });
});
  1. Check all the console-logs.

  2. Another thing…reading once again your description…found…

The problem: If I switch the gender, and switch it back in the initial position for example ( From Women to Men, and back to the Women) The actualProduct which I use to take the brand image is returned null. The actualProduct is giving me the product and using .include(brand) is letting me navigate through the brand item from an another dataset, from where I get the black version of the logo (“logoblack”). This is irelevant, why is this happening. Nothing changes, why is returning a null object.

WHAT ??? ----> you are using a —> DATASET ?
Where is your dataset inside your code?
Is your dataset already —> READY <— when you start to work with it?

Or did you want to say —> Database intead of DATASET ???

If you are using a DATASET → this would change ----> EVERYTHING !!!

And next time try not to write a whole roman of description.
It would be ok, if you would provide just the main important things someone has to know, like…

  1. I am using a dataset…(dynamic/non-dynamic) with the ID…
  2. I have a database with the ID …
  3. My dataset is connected to the DB with the ID …
  4. I am working on a —> Product-Page
  5. I have a repeater on that product page… with the ID…
  6. and so on…
  7. here my working/not working code…

My question…

Done…

If that still not work, take a look onto CONSOLE-LOGS.
Make a screen of the LOGS → and show a PICTURE of the log here (+describe the issue).

Hi again!
Yes actually I was refering to a collection. I discovered why the code is not working for getting back to the previous gender.

  1. In my Initial Code → initRepeater() → The itemData is not returning the full item second time (a cache problem maybe) when I call " $w ( ‘#productList1’ ). onItemReady ( async ( $item , itemData )" . Is not returning ‘product._id’ anymore, ‘product’ being a referenced field to an actual product in my wix store.

  2. In MyAll2 → an item from here have a field referenced to ‘brands’ collection (I will provide ss)

  3. In MyAll2 → an item from here have a field referenced to the wix store products (I will provide ss)

This is first time:

This is second time, the same gender:


As you can see, the referenced product is not included anymore.

This is the MyAll2 Collection -->‘Product’ is : itemData item(in our example) / Wix store product

This is the brands collection:

I think you will be able to solve your problem, if you continue to use CONSOLE-LOGS on right places inside your code.

It is a little bit difficult to help you not having the project infront of my eyes.
Your issue seems to be a little bit tricky.

The best wys to DEBUG issues → CONSOLE-LOGS + investigation of RESULT-BEHAVIOUR.

I would have to reconstruct your situation first to be able to give you more help, but no time for that, sorry.

If you still do need help at the end and you are not able to solve it, you can contact me (you will find my e-mail in my profile).

An invitation to your site and i am able to invetigate your issue directly.:wink:

Thank you so much. I will keep this in mind!

Have a great day!