Unable to access the Vuex state within a Vue component

Upon logging in, I am attempting to retrieve user data. However, instead of an array of users, it is returning an Object.

Code

Main component (App.js)

<script>
    export default {
        data() {
            return {
                user: ''
            }
        },
        computed : {
            isLoggedIn() {
                return this.$store.getters.isLoggedIn
            }
        },
        methods: {
            logout: function () {
                this.$store.dispatch('logout')
                .then(() => {
                    this.$router.push({name: 'home'})
                })
            }
        },
        created: function () {
            this.user = this.$store.getters.loggedUser
            console.log('user data', this.$store.getters.loggedUser) //returns Object
        }
    }
</script>

Store.js

import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'
Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    status: '',
    token: localStorage.getItem('access_token') || '',
    user : {}
  },
  mutations: {
    auth_request(state){
        state.status = 'loading'
      },
      auth_success(state, token, user){
        state.status = 'success'
        state.token = token
        state.user = user
      },
      auth_error(state){
        state.status = 'error'
      },
      logout(state){
        state.status = ''
        state.token = ''
      },
  },
  actions: {
    login({commit}, user){
        return new Promise((resolve, reject) => {
          commit('auth_request')
          axios({url: '/api/auth/login', data: user, method: 'POST' })
          .then(resp => {
            const token = resp.data.access_token
            const user = resp.data.user
            localStorage.setItem('access_token', token)
            axios.defaults.headers.common['Authorization'] =  'Bearer ' + token
            commit('auth_success', token, user)
            resolve(resp)
          })
          .catch(err => {
            commit('auth_error')
            localStorage.removeItem('access_token')
            reject(err)
          })
        })
    },
    register({commit}, user){
        return new Promise((resolve, reject) => {
          commit('auth_request')
          axios({url: 'api/auth/register', data: user, method: 'POST' })
          .then(resp => {
            console.log('register data', resp);
            const token = resp.data.access_token
            const user = resp.data.user
            localStorage.setItem('access_token', token)
            axios.defaults.headers.common['Authorization'] =  'Bearer ' + token
            commit('auth_success', token, user)
            resolve(resp)
          })
          .catch(err => {
            commit('auth_error', err)
            localStorage.removeItem('access_token')
            reject(err)
          })
        })
      },
      logout({commit}){
        axios.defaults.headers.common['Authorization'] = 'Bearer ' + this.state.token
        return new Promise((resolve, reject) => {
        axios({url: 'api/auth/logout', method: 'POST' })
          .then(resp => {
            commit('logout')
            localStorage.removeItem('access_token')
            localStorage.removeItem('token_type')
            delete axios.defaults.headers.common['Authorization']
            resolve()
          })
          .catch(err => {
            commit('logout')
            localStorage.removeItem('access_token')
            localStorage.removeItem('token_type')
            delete axios.defaults.headers.common['Authorization']
            reject(err)
          })
        })
      }
  },
  getters: {
    isLoggedIn: state => !!state.token,
    authStatus: state => state.status,
    loggedUser: state => state.user,
  }
});

export default store;

Note: In reference to this answer, I have added

loggedUser: state => state.user,
to my getters. However, I am only receiving an object and not the expected user data.

Screenshot

https://i.sstatic.net/XbVZb.png

Question

How can I successfully obtain my user data within my component?

Answer №1

Is it not just within the value?

this.data.value

Answer №2

It is recommended to fetch user information after the user has successfully logged in, rather than during the creation of the App component. This ensures that the user is authenticated before accessing their data.

Answer №3

Problem Solved!

After facing difficulty retrieving user info from the Vuex state, I made the decision to limit the user data fetched from the backend and store it in localStorage. By doing this, I am able to easily access my user data from storage instead of relying solely on Vuex.

Updated Code Snippets

store.js

login({commit}, user){
    return new Promise((resolve, reject) => {
        commit('auth_request')
        axios({url: '/api/auth/login', data: user, method: 'POST' })
        .then(resp => {
        console.log(resp)
        const token = resp.data.access_token
        const user = resp.data.user
        console.log(user)
        localStorage.setItem('access_token', token)
        localStorage.setItem('user', JSON.stringify(user)) // added this line
        axios.defaults.headers.common['Authorization'] =  'Bearer ' + token
        commit('auth_success', token, user)
        resolve(resp)
        })
        .catch(err => {
        commit('auth_error')
        localStorage.removeItem('access_token')
        localStorage.removeItem('user')
        reject(err)
        })
    })
},

App.vue (main component)

I replaced the created() function with the mounted() function for better functionality.

mounted() {
    const user = JSON.parse(localStorage.getItem('user'));
    const state = user
        ? { status: { loggedIn: true }, user }
        : { status: {}, user: null };
        if(user){
            this.user = user.name
        } else {
            console.log('nothing')
        }
}

This approach has resolved any errors occurring for visitors or logged-in users. Additionally, I can now retrieve the user's name immediately after logging in.

I hope this solution proves helpful to others experiencing similar issues.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Decrease one of the two values in Mongoose

My User schema consists of two fields: var userSchema = mongoose.Schema({ credits : { type: Number }, energy: { type: Number }, }); I am currently working on a method to decrement one of the values based on the other. The logic is simple - if the ...

When utilizing jQuery lightbox to pull data from a database using PHP/Ajax, it may require a double click the

Encountering a strange issue where I must click on specific buttons with unique IDs. These IDs are then sent through Ajax to a PHP script, which searches for corresponding entries in the database. The retrieved data is then displayed in a jQuery lightbox. ...

The issue of a false value not being correctly matched in Jasmine is causing problems

Currently, I am utilizing the following code to evaluate an element with aria-checked="false". expect((accessPolicyPage.listSelectAll).getAttribute("aria-checked")).toEqual("false"); The output is presenting as Expected [ 'false' ] to equal &ap ...

Manipulate JQuery plug-in properties within an AJAX request using MVC

Currently, I am utilizing a Jquery time picker sourced from Within the view, there exists this time picker control. $("#startTime").timePicker({ startTime: "09.00", endTime: new Date(0, 0, 0, 19, 0, 0), show24Hours: false, ...

What is causing the width discrepancy in my header section on mobile devices?

Help needed with website responsiveness issue! The site works fine on most screen sizes, but when it reaches around 414px in width, the intro section becomes too wide for the screen. Any ideas on what could be causing this problem? html: <nav id="m ...

Execute a JavaScript function on a Node server following a click event in an HTML document

Hello everyone, I am currently working on a project using node.js in a Windows environment. With the help of the express module, I am trying to create a static page that includes a Submit form. When someone clicks the "Submit" button, I intend to execute a ...

Issue with Vue3 :style backgroundImage not functioning correctly when using require

Attempting to transition a Vue 2 project to Vue 3. In Vue 2, the v-bind style was used as shown below: <div :style="{backgroundImage: 'url('+require('/assets/imgs/'+ project.img)+')'}"></div> In Vue 3, t ...

Oops! The type in React.jsx is not valid - it should be a string for built-in components. You may want to consider converting your class component to a

The error message I am encountering is as follows: React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it&ap ...

Uploading a file using AngularJs

When it comes to uploading an image or file using HTML tag in AngularJS, it seems that the tag is not supported. The solution? Create a custom directive. In my index.html page, I included the following code: <body ng-controller="myController"> ...

Manage multiple sessions at the same time

In a specific scenario, we face the need to manage multiple sessions similar to Google Accounts. Users should be able to add different accounts in separate tabs, each with its own unique content. For example, user1 may be logged in on Tab1 while user2 is l ...

Using TypeScript for Immutable.js Record.set Type Validation

Currently, I'm utilizing Immutable.js alongside TypeScript for the development of a Redux application. In essence, the structure of my State object is as follows: const defaultState = { booleanValue: true, numberValue: 0, } const StateRecord = ...

What is the best way to send a parameter to the callback function of a jQuery ajax request?

I am facing an issue where I need to pass additional variables to a jQuery ajax callback function. Consider the following scenario: while (K--) { $.get ( "BaseURL" + K, function (zData, K) {ProcessData (zData, K); } ); } func ...

Error: Unable to access the 'category_affiliation' property of null

After implementing a login function using redux state, I encountered an issue upon logging in. The error message TypeError: Cannot read properties of null (reading 'category_affiliation') is being displayed in my Sidebar.jsx file. It seems like t ...

The Ionic Capacitor "PushNotifications" plugin is currently not supported on Android devices

I'm encountering an issue while attempting to request permissions using the @capacitor/push-notifications plugin. I have carefully followed all the steps outlined in the README and am working with Ionic and Vue 3. Here is a snippet from my package.js ...

There was an unexpected token syntax error while trying to assign the database URL from the environment variable "REACT_APP

I am facing an issue with setting an environment variable in my mongo.js file. Here is the code snippet where I have set the ENV variable: const mongo = require('mongodb').MongoClient; const assert = require('assert'); const ObjectId = ...

The Angular method for retrieving the child's ID when it is clicked

As a newcomer to Angular 1.0 with a background in jQuery, I am facing the following scenario: Let's imagine we have the following HTML structure : <div id="filters"> <div id="filter1">Filter 1</div> <div id="filter2"> ...

Using JavaScript, post an image to imgur (API version 3) from a canvas

Currently, I am working on an amusing Chrome experiment called the Mustache Mirror! If you're interested, you can check it out here. I am aiming to incorporate the Imgur API V3 for uploading an image from the canvas to Imgur and displaying the link. U ...

Unable to retrieve the IDs of various products using AJAX

Struggling with creating an E-commerce site using PHP and AJAX, I'm facing an issue fetching product IDs on my shop view. My shop consists of 3 products with IDs 1, 2, and 3. When a user clicks the "Add to Cart" button, I want to retrieve the corresp ...

Troubleshooting React on an Apache Server: A Comprehensive Guide

An interactive React application utilizing React Router has been successfully deployed on an Apache server. After making modifications to the .htaccess file, most of the routes function correctly as intended. Some specific routes within the app rely on us ...

Error encountered: Javascript throws an error while trying to initialize the Bootstrap datetimepicker if the input value only

My requirement is to utilize the DateTime Picker plugin and load only the Time picker component. To achieve this functionality, I have initialized my input field in the following manner, allowing only time selection: jsfiddle: <div class="input-group ...