(pinia, vuex) I am having trouble accessing states and getters in main.js. What could be the reason for this issue?

Issue Resolved While the answer provided by @Po Wen Chen below was somewhat helpful, it didn't fully meet my requirements. Although data in proxy form continued to flow, the conditions were being met.

The main issue was that every time the page was refreshed, the states became null and their values disappeared. After some research, I managed to make my states persistent using a library called pinia-plugin-persistedstate. Issue Resolved

Following the documentation, I implemented the solution but instead of receiving user data, I was getting data of type proxy.

View pinia documentation on using store outside component

The account store handles user registration and login processes.

import axios from "axios";
import { defineStore } from "pinia";

const useAccountStore = defineStore("account", {
  state: () => ({
    user: null,
    returnUrl: null
  }),
  getters: {
    isLoggedIn: state => (state.user ? true : false),
    getUser: state => state.user,
  },
  actions: {
    async init() {
      console.log('run the init')
      this.fetchUser()
    },
    async registerUser(user) {
      await axios.post("/account/register", {user})
    },
    async login(credentials) {
      const user = await axios.post("/account/session", credentials)

      this.user = user.data
    },
    async logout() {
      await axios.delete("/account/session")

      this.user = null
    },
    async fetchUser() {
      const user = await axios.get("/account")

      this.user = user.data
    },
  },
})

export { useAccountStore };

In main.js

import antd from "ant-design-vue"
import "ant-design-vue/dist/antd.css"
import axios from "axios"
import { createPinia } from "pinia"
import { createApp } from "vue"
import App from "./app.vue"
import { router } from "./router"
import { useAccountStore } from "./store/account.store"

axios.defaults.baseURL = import.meta.env.VITE_API_URL
axios.defaults.withCredentials = true

createApp(App)
  .use(createPinia())
  .use(router)
  .use(antd)
  .mount("#app")

useAccountStore().init()

router.beforeEach(async (to) => {
  // redirect to login page if not logged in and trying to access a restricted page 
  const publicPages = ['/login', '/register'];
  const authRequired = !publicPages.includes(to.path);
  const authStore = useAccountStore();

  console.log('authStore.isLoggedIn', authStore)

  if (authRequired && !authStore.user) {
      authStore.returnUrl = to.fullPath;
      return '/login';
  }
});

When I log the authStore to console, it appears as a proxy object.

See the proxy displayed

Answer №1

While @Po Wen Chen's response below was somewhat helpful, it didn't quite solve my problem as I had hoped. The data keeps coming in the form of a proxy, which is not a big deal as long as the conditions are met.

The main issue was that every time the page refreshed, the states would reset to null and their values would disappear. However, after some research, I found a solution by using the library called pinia-plugin-persistedstate to make my states permanent.

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

Struggling to retrieve dynamic information from innerHTML in Angular

I am extracting live data from my view or HTML and displaying it on my page to visualize the output of that information. I need to follow this approach because I am designing a custom print page with this real-time data. The technique I am currently using ...

The dropdown menu in Mantine is malfunctioning, even though I copied and pasted the exact code from

While following a tutorial, I encountered an issue with the Mantine Menu and Dropdown components. The tutorial creator did not wrap the React App inside the MantineProvider, which resulted in errors when trying to use the Dropdown component. Even after add ...

Tips for recalling the display and concealment of a div element using cookies

My HTML code looks like this: <div id='mainleft-content'>content is visible</div> <div id="expand-hidden">Button Expand +</div> To show/hide the divs, I am using JQuery as shown below: $(document).ready(function () { ...

How can I use JavaScript to retrieve information from a different webpage?

I am trying to extract data from another webpage using JavaScript, jQuery, or Ajax without using PHP. I came across a helpful example on Stack Overflow (link here). However, when I implement these codes in my index.html file, it doesn't seem to work. ...

Optimizing Nginx for caching server-side rendered (SSR) web pages developed using React and Next.js

After creating an application where some pages are rendered on the server side, I noticed that something wasn't right. When viewing the requested pages in my browser, everything seemed normal. However, when I sent a CURL request to the page and saved ...

How can we bring in prop array values in React?

I've been working on developing a small music player program in React. Is there a way to import all these values together with a single import statement? I noticed that manually inputting the values into the props array doesn't work because the ...

Combine the values of identical keys from multiple objects in an array by utilizing the forEach method in JavaScript

I am currently working on refining a shopping basket function with Vue JS. One of the key features I need to implement is a subtotal calculation that multiplies the price and quantity values for each item and then combines them to create an overall subtota ...

Unveiling the Magic Bytes: Extracting the Image File in Multer for Magic Byte Verification in Express.js

Utilizing the fileFilter option within the multer plugin to determine whether an image should be saved on the server or not. Within the fileFilter function, there is a need to verify the magic bytes of these images in order to ensure they are legitimate a ...

Display your StencilJs component in a separate browser window

Looking for a solution to render a chat widget created with stenciljs in a new window using window.open. When the widget icon is clicked, a new window should open displaying the current state while navigating on the website, retaining the styles and functi ...

Incorporate imagesloaded.js into your PHP script to seamlessly import images from a designated folder

I've implemented the code below into a bootstrap modal to display images from a website folder. These images are loaded using lazyload.js when the modal is opened. Sometimes, there's a delay in displaying images depending on their sizes. I'd ...

The animated loading image is taking an eternity to actually load

My website is loaded with heavy front-end features and I'm using a loading gif to help with the loading process. However, I've noticed that in Safari, there is a delay before the gif loads after the background does, which takes away from the inte ...

Undo changes in Sequelize transaction using a specific rollback target

In my current project, I am utilizing managed transactions. There is a specific scenario where I need to implement a single transaction and revert to a certain savepoint if it encounters an error, but still ensure that the changes are committed in the end. ...

What is the best way to ensure that all website users receive the same update at the same time using AngularJS and Firebase?

Imagine a scenario where I and my 3 friends are accessing the same website from different computers simultaneously. Each of us has a profile stored in an array like this: $scope.profilesRanking = [ {name:"Bob", score: 3000}, {name:"John", score: 2 ...

Rotating a specific part of a model in THREE.js

Whether it's feasible to adjust the position or rotation of a component within an OBJ (or similar format) model. Can one manipulate a single model instead of needing multiple ones? What is the optimal approach to achieve this goal effectively? Appreci ...

Is it possible to redirect the client to a different HTML file after they input a number?

Following a submission of numerical input, I am looking to navigate from the index.html file to another HTML file or similar destination. Could someone provide assistance? Below is the code I have written: <!DOCTYPE html> <html lang="en&quo ...

Tips for effectively utilizing tags in AngularJS search functionality

I attempted to implement a search box that utilizes tags, shown in the image below. Despite trying to use bootstrap tags, it did not work as intended. Here is a visual representation of how the search should be displayed: https://i.sstatic.net/COqai.png ...

How do I retrieve a specific object value from a JSON API using an index within a forEach loop in JavaScript?

Over the weekend, I decided to delve into learning how to utilize fetch() APIs. While exploring an interesting API service, I encountered a little hiccup with javascript. The Issue Although I successfully fetched the data from a .Json file, I faced diffi ...

What sets apart using `: Interface` versus `as Interface` in Typescript?

I'm struggling to find the distinction between two similar lines of code due to uncertainty about what they are called. Consider the scenario where the following interface is defined: interface Person { name: string; age: number; } What exactly ...

Convert the values from the table cells into an array

Recently, I've been working with jQuery to extract an array from table cells, format the data, and pass it into a JavaScript function. The code snippet I have implemented is as follows: var l1 = new Array(); $('table#datatable tbody td:firs ...

Storing Personalized Information in Thingsboard; Beyond Telemetry Data

I am currently utilizing the amazing platform of thingsboard. Imagine I have a basic User Form with the following fields: Username First Name Last Name Email Address Phone Number My goal is to store all this information in thingsboard. Can thingsboard h ...