onLogout( ) event handler issue

I use a Wix authentication panel on my site, and I’d like to know if users are currently logged in or logged out, to define different scenarios, like sending automated email notifications to a user only if that user is logged out at the moment, and other staff. So I created a “Users” DB with an 'isLoggedIn" field (true/false).

When a user logs in, the field value is set to “true” (this part works), but when I put a code into onLogout( ) event handler, nothing happens - the value remains as “true”. I thought the problem could be the code is called after logout is comleted, so DB change can’t be made since there is no process’s owner left by that moment, but not really sure. I also tried to use an < authentication . logout (); > function, but got the same result. Seems like it’s not possible to call anything besides a console.log function when a user logs out.

Below is the code structure I use in a Master Page code panel. Any advice on how to make it work?

import { authentication } from 'wix-members';

$w.onReady(function(){

    authentication.onLogout(() => {
	// my code which is supposed to set 'isLoggedIn' field value to false in a "Users" collection.
    })
    
})

What is the code that isn’t working? Share your code so we can see what you are trying to do. Keep in mind that you should be writing to the DB collection from backend code with suppressAuth set to true .

1 Like

Thank you Yisrael, my mistake was that all the code was on a frontend side, and with no any supress options. Now after your help it works, thanks again!!!

I’ll share an updated code below, hope it could be helpful for others.

Frontend code (masterPage.js)

import { authentication } from 'wix-members';
import {loginState} from 'backend/data.jsw';

import wixUsers from 'wix-users';

let user = wixUsers.currentUser;
let userId = user.id;


$w.onReady(function() {

    authentication.onLogout(()=> {
    
        loginState(userId)
        
    })
    
})

Backend code (data.jsw)

const Users = 'Users';

export function loginState(userId) {

  wixData
        .query(Users)
        .eq('userId', userId)
        .limit(1)
        .find()
    .then( (results) => {

    let res = results.items
    let length = res.length   

    if (length > 0) {

      let id = res[0]._id

      let options = {
      "suppressAuth": true,
      "suppressHooks": true
      };

    wixData.get(Users, id, options)
    .then( (item) => {
      item.isLoggedIn = false;
      wixData.update(Users, item);
    } )
    .catch( (err) => {
      let errorMsg = err;
    } );

  }

  })

}
1 Like