I have a composable useAuth
that deals with authentification. If successful, I want to save the current user in my store.
Should the business logic happen in this composable, which in turn calls an action of my store "setUser", or should the whole action deal with it? What do I need my composable for then?
Also, do I really need a dedicated action "setUser" to mutate the state, or could I mutate it directly? Opinions about this vary online ... 🤔
Yes, you need a dedicated action "setUser" to change the state, or you can change it directly.
use like that type of your Business logic structure.
useAuth.js
import { ref } from 'vue';
import { useStore } from 'pinia';
export function useAuth() {
const store = useStore();
const isAuthenticated = ref(false);
async function login(username, password) {
// Perform authentication logic here (e.g., API request).
// If authentication is successful, set isAuthenticated to true.
// You can also retrieve user data at this point.
isAuthenticated.value = true;
// Call the store action to set the user in the global state.
store.setUser({ username, /* other user data */ });
}
function logout() {
isAuthenticated.value = false;
// Clear user data in the store if necessary.
store.clearUser();
}
return {
isAuthenticated,
login,
logout,
};
}
store.js
import { defineStore } from 'pinia';
export const useAuthStore = defineStore('auth', {
state: () => ({
user: null,
}),
actions: {
setUser(user) {
// Use an action to set the user in the store's state.
this.user = user;
},
clearUser() {
// Use an action to clear the user from the store's state.
this.user = null;
},
},
});
LoginComponent.vue
<template>
<div>
<button @click="login">Login</button>
<button @click="logout">Logout</button>
</div>
</template>
<script>
import { useAuth } from './useAuth';
export default {
setup() {
const { isAuthenticated, login, logout } = useAuth();
return {
isAuthenticated,
login,
logout,
};
},
};
</script>
I hope it work for your requirement Thank you.