I'm new to using Vue and Pinia I want to show logged in user first_name & last_name, but when I want to access the user id after logged in, it returns undefined could you please help me to fix this problem actually I can access these infomations on the login page, but I want to access them right after login, when redirect to home page and go to other pages
Here is my pinia login store:
import { defineStore } from 'pinia'
import { axiosAPI } from '../axios'
export default defineStore('login', {
state: () => ({
user: [],
isLoading: false,
isuserLoggedIn: false,
token: '',
userInfo: [],
isRedirect: false,
userId: '',
}),
actions: {
async loginUser(values) {
this.isLoading = true
await axiosAPI
.post('user/login', values)
.then((response) => {
console.log(response)
this.isLoading = false
const data = response.data.data.payload
if (data) {
this.user = data
this.isuserLoggedIn = true
this.token = data.token
localStorage.setItem('token', this.token)
this.userId = this.user.id
this.isRedirect = true
setTimeout(() => {
window.location.href = '/home'
this.isRedirect = false
}, 20000)
}
})
.catch((error) => {
this.isLoading = false
})
this.getInfo(this.userId)
},
},
persist: true
})
here is my profile component:
<template>
<p
class="sm:text-neutral-950 sm:block hidden sm:text-sm sm:font-light pl-4"
:class="userProfile"
></p>
{{ userProfile }}
</template>
<script>
import useLoginStore from '../stores/login'
import { mapStores } from 'pinia'
export default {
name: 'Profile',
data() {
return {
usr: useLoginStore(),
}
},
computed: {
...mapStores(useLoginStore),
userProfile() {
return `${this.usr.userInfo.first_name} ${this.usr.userInfo.last_name}`
}
},
}
}
</script>
To prevent the loss of the userId when the page is refreshed, it's crucial to persist it in the local storage. This ensures that the user's identification remains intact even after a page reload. In the code snippet, the userId is stored using localStorage.setItem('userId', this.userId), ensuring its retrieval and preservation across sessions.
Then Hit the API Call with userId.