Unable to assign role upon member registration

I’m unable to get the following code to assign a role to members upon registration. Would really appreciate if anyone could please point out what’s wrong. Thanks!

// Custom signup

import { authentication } from 'wix-members';
import { assign } from 'backend/role';

$w.onReady(function () {

    // Click "Run", or Preview your site, to execute your code
    $w('#button2').onClick ((event) => {
        const email = $w('#input2').value;
        const password = $w('#input1').value;
        const options = {
            contactInfo: {
                firstName: $w('#input4').value,
                lastName: $w('#input3').value
            }
        };
        var role = "";
        if ($w('#dropdown1').value=="Employer") {
            role = "c02c480a-20ae-4cd7-85ff-d0d00d60ecda";
        } else if ($w('#dropdown1').value=="Employee") {
            role = "32c341be-8b80-4dec-ab82-8d39f729680c";
        }
        console.log(role);
        authentication.register(email, password, options).then((results) => {
            console.log("Hit correct branch");
            assign(results.member._id, role);
            console.log("Successfully assgined role");
        })
        .catch((error) => {
            console.log("Hit error branch");
            console.error(error);
        };
    });

});
// backend/role.jsw

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

export function assign(member, role) {
    const roleId = role;
  const memberId = member;

  return authorization.assignRole(roleId, memberId, {suppressAuth: true})
    .then(() => {
      console.log("Role assigned to member");
    })
    .catch((error) => {
      console.error(error);
    });
}

When I try to sign up and open the web console, only the role ID would be printed (console.log(role)) but “Hit correct branch” would not be printed.

1 Like

Do you get results at this point …?

authentication
.register(email, password, options)
.then((results)=>{
    console.log("RESULTS: "; results);
});

Is the role/role-ID already included inside the resulting-object, at this point?

Directly after the registration you gets logged-in. This causes a page-reset.

But wait!!! What??? → You get automatically logged-in !!!

Ok, maybe you need to use in this case an → “onLogin()” event-trigger???

Something like…

MASTER-PAGE:

$w.onReady(()=>{
	wixMembers.authentication.onLogin((member)=> {
		console.log("Member: ", member);
	});
});
2 Likes