top of page

Tutorials and Code Examples

Incentivize Your Users With The Badges API

Thu Jul 28 2022

2.gif
Blank_Canvas_on_Transparent_Background.p

Share

  • Twitter
  • Black LinkedIn Icon
  • Facebook

Gamification in web design is a concept used to apply game-like elements to your website to increase user engagement and retention. Some...

Gamification in web design is a concept used to apply game-like elements to your website to increase user engagement and retention. Some examples of gamification include using a points system, user levels, or competition to drive certain behaviors. In this article we will explore gamification through a custom implementation of the Badges API.


What are Member Badges?


In your WiX site, member badges are a feature available as part of the members area that allows you to create and connect custom badges to your users. Applying badges to users in your WiX site does not require any code. You can create and assign member badges from the dashboard and even apply page based permissions through these badges. The badges you create will then show automatically connected to each members’ profile.


Custom Member Badges


With the Badges API, we have more control over how badges are assigned and displayed on our website. To demonstrate customizing badges and applying simple gamification concepts we will create an example page that shows the logged in user what badges are available and what badges they have. This example will also include updating the current users badges in a repeater when they complete the required action to obtain a badge.


Requirements: To complete this exercise, you must install the Members Area on your site.


To begin, we will create two custom badges in the dashboard of our site. You can find the badges area by navigating under Contacts → Site Members and then click on the blue Manage Badges button.

On the next screen, click on + New Badge and create 2 badges. One of the badges we will manually assign and the other should look like this image below. Note in the description we are describing to the user how to get the badge by writing “Click the Get Koala Badge Button”.

Note: In the URL of your badge is the ID that you will need later in this example. Copy this value and save it somewhere easy to retrieve. This ID is visible while you are on the edit screen of your badge and is the second GUID in the URL.

Next, navigate to your website editor and create a new page to display your badges. You may call this page anything you like. On this page add two blank repeater elements side by side. Assign an ID to the first repeater of #allBadges and the second and ID of #myBadges.

Next, drag two text elements and one image element onto your repeater and populate with some dummy data to be able to see your arrangement. You will complete this same task for your second repeater. Both repeaters should now look similar to this:

The first repeater element we will now hook up to a dataset as it will be used to display all available badges on page load. To hook up your Badges collection to the first repeater, click on the repeater and click the “Connect to Data” icon.

In the menu that opens click “Create Dataset” and in the dropdown choose the Badges collection.

Now that the Badges collection is available, we can map the values to the text and image elements in the repeater. Connect the two text elements to the Title and Description fields and your image to the Icon field. Once connected, the badges we created previously in the dashboard will automatically populate the repeater and look similar to the image below.

The #myBadges repeater will be populated based on the current site members badges. To set that up, first give the text elements and images specific ID’s. Give the title element an ID of #badgeName, the description badgeRules, and finally the image #badgeIcon. Then set the repeater to collapsed as it’s default loading state.

The Badges API is a backend only API therefore you will have to write code in the page to get the member ID and pass that to a function in the backend to get the badges associated with that member before returning this result to the front end and populating the repeater.


In your page add the following code:

import { currentMember } from 'wix-members';
import { getMemberBadges } from 'backend/getBadges'
import wixData from 'wix-data'

const options = {
   fieldsets: ['FULL']
}

$w.onReady(async function () {

   $w('#myBadges').data = []

   const loggedInMember = await currentMember.getMember(options);

   const memberBadges = await getMemberBadges(loggedInMember._id);

   if (memberBadges) {
       myBadges(memberBadges)
   }

function myBadges(memberBadges) {
   wixData.query("Members/Badges")
       .hasSome('_id', memberBadges[0].badgeIds)
       .find()
       .then((results) => {
           console.log(results.items)
           $w('#myBadges').data = results.items;
           $w('#myBadges').onItemReady(($item, itemData, index) => {
               $item("#badgeName").text = itemData.title;
               $item("#badgeRules").text = itemData.description;
               $item("#badgeIcon").src = itemData.icon;
           })
           $w('#myBadges').expand();
       });
}

Then create a backend jsw file called getBadges.jsw. You can create backend files by clicking on the { } in your left side navigation. In the file, add the following function.

import { badges } from 'wix-members-backend';

export function getMemberBadges(memberID) {

return badges.listMemberBadges([memberID])
   .then((memberBadges) => {
return memberBadges;
   })
   .catch((error) => {
console.error(error);
   });
}

Code Notes: In the page code we are getting the current member ID and passing it to the getMemberBadges function in getBadges.jsw. One important thing to notice is that the listMemberBadges function expects an array so even though we are only passing one ID at a time you must use the array format or there will be an error. Once the member badges function returns data to your page code, now we are using the WixData API to query for the attributes associated with the badge. We have to complete this step to get the title, description, and icon image as the backend API only returns the badge ID’s Finally we are populating the repeater and then expanding the repeater.


At this point you should publish your work and test the site to make sure that you are seeing the available badges and the badges for your logged in test user. Once you are happy with the progress, we can move on to the next step.


Navigate back to your editor and add a button to the page. Give the button an ID of #getKoalas. This is the action we want the user to complete to receive their next badge. We will now add more code that will assign the user the Koala badge when they click the button and refresh the member badges repeater so the user can immediately see their new badge.


First in the getBadges.jsw file, add a new function called getKoalaBadge()

export function getKoalaBadge(member) {
const badgeId = "your-badge-id";
return badges.assignMembers(badgeId, [member])
   .then((assignedMembers) => {
return assignedMembers;
   })
   .catch((error) => {
console.error(error);
   });
}

Code Notes: This function takes a user ID and assigns them a new badge. Make sure to add the badge ID for your koala badge. If you did not save this ID, you may find it by navigating to the dashboard and clicking edit on the badge you would like to assign through the getKoalaBadge function and then inspecting the URL.


In your page code, import the new backend function.

import { getMemberBadges, getKoalaBadge } from 'backend/getBadges'

Then inside your onReady function listen for the getKoalas button click

$w('#getKoalas').onClick(async () => {
    let koalas = await getKoalaBadge(loggedInMember._id);
    if (koalas) {
           updateBadgeRepeater(loggedInMember._id)
           $w('#koalas').show()
           $w('#koalas').expand()
    }
})

Code Notes: Notice that in this onClick event we start an asynchronous process that will await the result of our backend function. If the backend function returns data, we will update the repeater with the new badges.


Finally outside of the onReady function we will add the updateBadgeRepeater() function which will refresh the members badge data and update the UI.

function updateBadgeRepeater(memberId) {
   getMemberBadges(memberId).then((results) => {
if(results.length > 0){
       myBadges(results)
      }
   })

Code Notes: This function takes a member ID and then makes use of the functions we already wrote to repopulate the repeater.


Now you can publish your site and head to the front end to see the entire process in action! After logging in, navigate to your badges page and you will see your current badge plus the extra Koala badge and the button to get it. Clicking on the button should refresh your badges and you will now see that you have both badges.


If you would like to see this code in action before attempting it yourself, there is also a video version on our YouTube channel.


Wrapping Up


Gamification is a great way to add some fun and interactivity to your website by tapping into intrinsic motivation. Giving users badges for completing different actions on your website is one way to add value for your users and keep them engaged with your website.





Blank_Canvas_on_Transparent_Background.p

0

get certified.png

Related Posts

View All

1.png

CORVID LIBARY

Unified Database Management

Unified Database Management

Jun 18, 2018   8min

1.png

CORVID LIBARY

Unified Database Management

Unified Database Management

Jun 18, 2018   8min

1.png

CORVID LIBARY

Unified Database Management

Unified Database Management

Jun 18, 2018   8min

bottom of page