agm1984
agm1984

Reputation: 17170

In vue-router middleware, how to detect page reload but ignore other route changes

I'm trying to make it so that I run a hydration function only when the browser is reloaded, not when every route changes. For example, I have this vue-router middleware:

router.beforeEach(async (to, _, next) => {
    const auth = useAuthStore();
    let isAuthenticated = false;
    if (to.meta.requiresAuth) {
        isAuthenticated = await auth.checkAccessToken();
    }

    if (isAuthenticated) {
        const agency = useAgencyStore();
        agency.loadAgency();

        if (to.meta.redirectsWhenAuthenticated) {
            return next({ name: 'dashboard.index' });
        }

        return next();
    }

    if (!to.meta.requiresAuth) {
        return next();
    }

    toast.warning('Your session has expired.');
    return next({ name: 'login' });
});

I'm trying to add logic into it where it will have an additional if statement, such as:

if (page was just reloaded) {
    agency.loadAgency();
}

Right now the above logic fires every time the route changes, such as even when the query strings change, so it's spamming my backend a bit. I want to make it so normal route changes don't fire agency.loadAgency(); only when the page is hard reloaded such as pressing F5.

I had code like this in an old app I made, so I'm pretty sure it's possible. Something like:

const START_LOCATION = from.fullPath;

if (!START_LOCATION) {
    // perform reload logic
}

I'm open to alternate ideas such as hydrating the app in App.vue created lifecycle. Any help is appreciated.

Additional info:

Upvotes: 1

Views: 3295

Answers (1)

agm1984
agm1984

Reputation: 17170

The correct answer here is to use vue-router START_LOCATION in the middleware. Here is an example:

import { START_LOCATION } from 'vue-router';

router.beforeEach(async (to, from, next) => {
    if (from === START_LOCATION) {
        console.log('this fires on page reload only, not every route change');
    }
});

https://router.vuejs.org/api/#start-location

Upvotes: 3

Related Questions