Detecting logged in status in a builder page

Hi

On the load of my builder page, I obtain the logged in status using the custom code below (entered in the data tab). This works fine. The player can then log in using a button in the header. The login process is via a right-hand slider and the player doesn’t leave the actual page.

As the player doesn’t leave the page then the custom code doesn’t run, and the logged in status of the page is out of sync.

Any suggestions how I handle this? I know this is a vague question, but I really don’t know how to add more detail!


function fetchGqlFsbToken() {
  const token = sessionStorage.getItem('gql_jwt');
  const bearer = 'Bearer ' +  token;
  if (token !== undefined) {
      fetch('https://t****.com/qa_graphql', {
        method: 'POST',
        body: JSON.stringify(FsbTokenQuery),
        headers: { 'Authorization': bearer,
                    'content-type': 'application/json' }
      })
        .then((response) => response.json())
        .then((data) => {
          if (data.data.customerV2 != null) {
            state.customerId = data.data.customerV2.customer.customerId;
            state.fsbToken = data.data.token.fsbToken;
            state.displayName = data.data.customerV2.customer.username;
          } else {
            console.log(data.errors[0].message);
          }
        })
        .catch((error) => { console.error('Error:', error); });
  }
}

async function getFsbToken() { await fetchGqlFsbToken(); }

const FsbTokenQuery = 
  { query: '{ token { fsbToken } customerV2 { customer { customerId username } } }' };

async function main () {

  if (Builder.isServer) {
    console.log("running on server side");
  }

  if (Builder.isBrowser) {
    var w = window.innerWidth;
    if (w <= 640) state.device = "mobile";
    else state.device = "desktop";

    state.isLoggedIn = !!sessionStorage.getItem('gql_jwt');
    console.log("isLoggedIn", state.isLoggedIn);
    if (state.isLoggedIn) {
        await getFsbToken();
    }
  }
}

export default main();

Hi @Richard_at_the_pools,

Could you please share your builder content link associated with this issue?

I could, but it is behind a VPN so you won’t be able to see it.

Can you confirm when mail() runs? I assume it is only on page load. Are there other events that builder.io supports automatically?

Hi @Richard_at_the_pools,

The main runs after the page render static contents. Does it work in preview mode?

You can try declaring the code outside the main and see if that works.

Where would I declare the code outside of main? In the same place under data tab/custom code

Hi @Richard_at_the_pools,

Yes, that’s right. Outside the main under the data tab or you can even try using custom code block.

1 Like