Connect custom element to dataset in wix & corvid

Viewed 700

Is there a way of using a dataset query inside of a custom element. On the support page (https://support.wix.com/en/article/custom-element-faqs) its says the following:

'Can I Connect Custom Elements to Data in a Collection?

Yes, you can connect custom elements to collections using Corvid's Data and Dataset APIs.'

But I don't know how to do it. I have have tried importing wixData from wix-data at the top of my custom element however this stops my custom element from displaying.

I need to create checkboxes based on the number of items in a dataset. I have been able to create the checkboxes based on a static array in the custom element but want to do it based on the dataset so I don't have to manually keep changing the array in the custom element.

Below is what I need in my custom element.

import wixData from 'wix-data';

wixData.query('testdata')
        .limit(1000)
        .find()
        .then(results => {
            console.log(results.items)
        });
1 Answers

You need to pass the Number of checkbox via attribute. Doc link

  $w('#customElementId').setAttribute('checkboxs-count', 5 );

Then on the custom element you need to listen for the attribute change. And update the UI based on that.

Here is a pseudo code

wixData module only exist on the Wix codebase. You need to import the data from the database using wixDatae and pass the data to custom element via setAttribute. like this

// page code
import wixData from 'wix-data';

wixData.query('testdata')
  .limit(1000)
  .find()
  .then(results => {
      // got the data from the database now pass the data to custom element using setAttribute method
      $w('#customElementId').setAttribute('checkboxs-count', results.length );
   });

And You need to write the custom element code to create the checkboxes and you can listen if the checkbox change and update the database via .on() method on the custom element selector.

so, the page code should look like this.

$w('#customElementId').on('checkbox-change', (event) => {
  console.log(`Checkbox Number ${event.detail.number} changed. Update Wix Database` );
  
});

Hope this explain how to communicate database with custom element.

Related