'Updating Vue state during navigation with vue-router

I'm building a Vue 3 app which uses Vue Router and Pinia for state management.

In my global state I'm defining a property which tells me if a user is logged in so the user can navigate through the app. However, the login process is being handled by Cognito, so once I enter the app, I click on the login button, it takes me to a Cognito screen which handles the login process and then redirects me back to my app's home page.

So after the redirect I extract some params from the resulting URL and I want to save them in the global state, for this I was using the beforeEach guard to parse the URL, check for the params, update the store and then reading from it to check the valid session.

But my issue was that the navigation continued even before the state was updated. I ended up using setTimeout just to see if waiting for a bit solved the issue and it did

    router.beforeEach((to) => {
  const mainStore = useMainStore();
  if (to.name === 'Login') {
    return;
  }

  if (to.hash !== '') {
    const queryParams = window.location.href.split('&');

    const paramValues = queryParams.map(param => {
    })

    const payload = {
      id_token: paramValues.find(param => param.name === 'id_token').value,
      access_token: paramValues.find(param => param.name === 'access_token').value,
      token_type: paramValues.find(param => param.name === 'token_type').value,
      isAuthenticated: true
    }

    //Here I'm trying to update my global state
    mainStore.updateTokens(payload);
  }

  // Here I use timeout, but before I just had the check for the property
  setTimeout(() => {
    if (!mainStore.isAuthenticated) return '/login';
  }, 3000)
});

How should I handled this case? I've read about the beforeResolve guard but I'm not sure on how to use it; basically I just need to know how should I go about performing some async operation (like fetching data from server) during the navigation, not inside components.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source