javascriptvuejs3profilepiniauserid

How can I use Logged in user id in another page?


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>

Solution

  • export default defineStore("login", {
      state: () => ({
        // ... (other state properties)
        userId: localStorage.getItem("userId") || "", // Retrieve userId from localStorage
      }),
      actions: {
        async loginUser(values) {
          this.isLoading = true;
          try {
            // Make a POST request to the login endpoint
            const response = await axiosAPI.post("user/login", values);
            console.log(response);
    
            // Update the loading state
            this.isLoading = false;
    
            // Extract user data from the response
            const data = response.data.data.payload;
    
            // Check if user data is available
            if (data) {
              // Update local state with user data
              this.user = data;
              this.isuserLoggedIn = true;
              this.token = data.token;
    
              // Store the token in localStorage for persistence
              localStorage.setItem("token", this.token);
    
              // Update the userId in local state
              this.userId = this.user.id;
    
              // Store the userId in localStorage for persistence
              localStorage.setItem("userId", this.userId);
    
              // Set a flag for redirection
              this.isRedirect = true;
    
              // Redirect to the home page after a delay
              setTimeout(() => {
                window.location.href = "/home";
                this.isRedirect = false;
    
                // No need to call getInfo here; it can be called in the created hook
                // of the home page or another appropriate lifecycle hook
              }, 20000);
            }
          } catch (error) {
            // Handle errors and log them to the console
            this.isLoading = false;
            console.error(error);
          }
        },
      },
    });
    
    

    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.