I need to create a question on the forum about how to create a separate “Log Out” button in the Wix Members area application. I am having trouble with the basic code not working. I want to be able to log out not through the profile picture or name, but by simply creating a button in the header and linking it to the Log Out function. Is this possible and if so, what code would be needed to achieve this? I would be very grateful for your assistance.
It is really simple. Just put this code inside the onClick event handler of your button. Something like:
Hi
The solution is to put the code into an onReady handler, as stated in the documentation.
Also it’s recommended that you use this code in the Site Page code, and not on a single site.
Here’s the code:
$w.onReady( function() {
$w('#logout').onClick(() => {
authentication.logout();
} );
Hello,
I’m experiencing an issue with Wix. I’m trying to use the ‘wix-members-frontend’ module for custom logout functionality, but I get an error: “cannot find module ‘wix-members-frontend’.” This error persists despite checks for typos and updates. Could you please help resolve this or suggest an alternative for custom logout implementation?
Thank you.
Where is your code ?
Это похоже была какая-то ошибка сейчас все ошибка не появляеться, но у меня проблема в обновлении интерфейса хедера, тоесть после входа я хочу чтобы интерфейс изменялся, он изменяеться но мне для этого вручную нужно перезагружать страницу, автомотически изменяеться только иконка входа на имя вошедшего профиля
Код:
import wixUsers from ‘wix-users’;
import wixData from ‘wix-data’;
import wixLocation from ‘wix-location’;
import { authentication } from ‘wix-members-frontend’;
// …
$w(‘#exit’).onClick(() => {
authentication.logout();
});
// Функция для обновления интерфейса
function updateUI(userType) {
if (userType === “Переводчик”) {
// Настройки для переводчика
$w(“#MenuTranslator”).show();
$w(“#hederZakaz”).hide();
$w(“#Myprofile”).show();
} else if (userType === "Заказчик") {
// Настройки для заказчика
$w("#hederZakaz").show();
$w("#MenuTranslator").hide();
$w("#Myprofile").show();
} else {
// Настройки для неопределенного типа
$w("#MenuTranslator").hide();
$w("#hederZakaz").hide();
showTypeSelectionBox(); // Показываем промпт-бокс для выбора типа
}
$w("#registerButton").hide();
$w("#LogoutMenuText").hide();
$w("#loginButton").hide();
}
// Функция для отображения промпт-бокса выбора типа профиля
function showTypeSelectionBox() {
$w(“#typeSelectionBox”).show();
}
// Обработчик для кнопки подтверждения выбора типа профиля
export function confirmTypeSelection_click(event) {
let selectedType = $w(“#profiletype”).value;
if(!selectedType) {
// Если тип не выбран, показываем ошибку
$w("#typeSelectionError").show();
return;
}
let userId = wixUsers.currentUser.id;
let userEmail = wixUsers.currentUser.getEmail();
// Сохраняем выбранный тип в коллекцию Register
wixData.insert("Register", { "_id": userId, "email": userEmail, "profileType": selectedType })
.then(() => {
$w("#typeSelectionBox").hide(); // Скрываем промпт-бокс
updateUI(selectedType); // Обновляем интерфейс с новым типом
})
.catch((err) => {
console.error(err);
});
}
$w.onReady(function () {
if(wixUsers.currentUser.loggedIn) {
wixData.query("Register")
.eq("_id", wixUsers.currentUser.id)
.find()
.then((results) => {
if(results.items.length > 0) {
let userType = results.items[0].profileType;
updateUI(userType);
} else {
// Тип пользователя не определен
showTypeSelectionBox(); // Показываем бокс для выбора типа
}
});
} else {
// Для неавторизованных пользователей
$w("#LogoutMenuText").show();
$w("#registerButton").show();
$w("#hederZakaz").hide();
$w("#MenuTranslator").hide();
}
});
wix-users is a deprecated API which is now replaced by the new wix-members API. So you will need to replace wix-users with wix-members-frontend and all the associated functions. You cannot use both at the same time.
Да, я могу это подтвердить, ваш подход устарел и не самый лучший. Вам придется адаптировать свой КОД, пересмотреть его.
Как уже упоминалось, API WIX-USER устарел и должен быть заменен WIX-MEMBERS.
Попробуйте это один раз и посмотрите, останутся ли у вас проблемы.
And if you still have problems, you can reach out again here.
thanks I’ll try to do that
Сейчас проблема только в том что при входе в аккаунт интерфейс хедера не изменяеться (автоматически), а когда жму кнопку выхода интерфейс хедера обновляеться как надо.
Да это верно.
Если вы войдете в систему → страница не обновится
Но если вы выйдете из системы → страница обновится.
И это совершенно правильно.
Чего вам не хватает → onLogin() <----
→ SEARCH FOR IT IN THE API-DOCS <—