Checking if there's a customer logged in

Hi! How can I check if there’s a customer (any customer) logged in? In the API v2 there was the method Snipcart.api.user.current(), but now in the v3 I can’t find anything similar…
Thanks in advance!
Cheers,
Fabricio
PS: the event customer.signedin is not enough for what I am trying to do.

Hey @Fabricio,

You can get the current user using our store API documented here.

Current user can be retrieved like this:

const customer = Snipcart.store.getState().customer;

You can use the status property to check if they’re logged in:

const customer = Snipcart.store.getState().customer;

if (customer.status === 'SignedIn') {
  alert("Customer is signed in!");
} else {
  alert("Customer isn't signed in");
}

If the customer is signed in, the status will be SignedIn, otherwise it will be SignedOut.

If you make the check on the page load, we recommend you wrap the code in the snipcart.ready event handler, and you’ll also need to subscribe to state change since the customer won’t be signed in in the initial state.

document.addEventListener('snipcart.ready', () => {
  let isCustomerSignedIn = false;

  Snipcart.store.subscribe(() => {
    const customer = Snipcart.store.getState().customer;
    isCustomerSignedIn = customer.status === 'SignedIn';
  });
});
1 Like

Thanks a lot, Charles!

1 Like