[Vuejs]-Vue 3 Composition Api , Vue-router 4 Naigation guards throw an Error when using it

1👍

Following the single responsability principle I suggest you to change the login() function on the store, remove the router push to let the store only authenticate your user. By doing this the redirection is handled by the calling funcion an not by the login.

AuthStore

import { defineStore } from "pinia";
import { ref, computed } from "vue";
import axios from "axios";

export const useAuthStore = defineStore("userAuth", () => {

    // .... 

    async function login(email, password) {
        try {
            const data = await axios.post("api/v1/users/login", {
                email: email,
                password: password,
            });

            if (data.status === 200) {
                userData.value = data.data;
                localStorage.setItem(
                    "user",
                    JSON.stringify(userData.value.data)
                );
            }
        } catch (error) {
            console.log(error);
            return (errorMessages.value = error.response.data.errorsToSend);
        }
    }
};

Router

import { useAuthStore } from "@/stores/auth.store.js";

// ...

router.beforeEach(async (to, from) => {
    const authStore = useAuthStore();
    const publicPages = ["/login", "/super-admin-login"];
    const authRequired = !publicPages.includes(to.path);

    if (authRequired && !auth.user) {
        return "/";
    }
});
👤Guille

Leave a comment