I am using Pinia for the first time. I am implemeting login feature with backend api which returns userId, I want store this userId in store and want to access it anywhere in vue component. Currently,I am not able to access the userId from store, it does not print the userId in vue template. Here is my code: Sores/user.js
import { defineStore } from 'pinia'
import axios from 'axios'
export const useUserStore = defineStore({
id: 'user',
state: () => ({
userId:null ,
}),
actions: {
login({ email, password }) {
axios.post('/user/login', { email: email, password: password }).then((res) => {
console.log('res',res.data.userId)
this.userId = res.data.userId
}).catch((error)=>alert('error'))
},
}
})
Login.vue
<script setup>
import axios from 'axios';
import { ref } from 'vue'
import { useUserStore } from '@/stores/user'
import { useRouter } from 'vue-router';
const email = ref('');
const password = ref('');
const userStore = useUserStore();
const router = useRouter();
const login = () => {
userStore.login({ email: email.value, password: password.value });
router.push('/dashboard')
}
</script>
Dashboard.vue here it want to print userId from store
<template>
<div id="dashboard">
<div class="row">
<div class="col-md-4">
<Header />
{{ userStore.userId }}
</div>
</div>
</div>
</template>
<script setup>
import Header from './Header.vue'
import { useUserStore } from '@/stores/user'
const userStore = useUserStore()
</script>
The problem is here:
const login = () => {
userStore.login({ email: email.value, password: password.value });
router.push('/dashboard')
}
You're pushing the change of route before logging in. You want to wait for the login request's response, then change the route, either with async/await
:
const login = async () => {
await userStore.login({ email: email.value, password: password.value })
router.push("/dashboard")
}
... or with .then()
:
const login = () => {
userStore.login({ email: email.value, password: password.value }).then(() => {
router.push("/dashboard")
})
}
Note the login()
action on userStore needs to return a promise.
Either return
the axios call (which is already a promise):
//...
actions: {
login({ email, password }) {
return axios.post(//...
...or "promisify" the action using async/await
:
//...
actions: {
async login({ email, password }) {
await axios.post(//...