Can you provide guidance on effectively utilizing a Pinia store with Vue3, Pinia, and Typescript?

I'm currently facing challenges while using the Pinia store with TypeScript and implementing the store within a basic app.vue Vuejs3 option api.

Here is my app.js file:

import {createApp} from 'vue'
import {createPinia} from "pinia";

import App from './App';
const pinia = createPinia()

const app = createApp(App);

app.use(pinia);

app.mount('#app');

Now, let's take a look at app.vue:

<script>
import {useAuthStore} from "@app/store/auth.store";
import {useCountryStore} from "@app/store/country.store";

export default {
  components: {SidebarMenu},
  setup() {
    return {
      authStore: useAuthStore(),
      countryStore: useCountryStore(),
    }
  },
  computed: {
    loggedIn: function () {
      return this.authStore.status.loggedIn;
    }
  }
}
</script>

Next up, we have authStore.js:

import {defineStore} from "pinia";

const user = JSON.parse(localStorage.getItem('user'));

export const useAuthStore = defineStore("auth", {
    state: () => (
        user ? {status: {loggedIn: true}, user}  : {status: {loggedIn: false}, user: null}
    ),
});

And now for CountryStore.ts:

import { defineStore } from "pinia";
import { Country } from "@app/interfaces/country";

export type CountryState = {
    countries: Country[],
    errors: any[],
}

export const useCountryStore = defineStore("country", {
    state: () => ({
        countries: [],
        errors: []
    } as CountryState)
})

In my particular scenario, I keep encountering an error related to countryStore but not AuthStore:

getActivePinia was called with no active Pinia. Did you forget to install pinia?

Interestingly, when I convert my countryStore.ts into .js (and remove type hinting), it works fine!

I've done extensive research trying to figure out what I'm missing or where I'm going wrong. I want to retain TypeScript in the end, but I'm unsure how to resolve this issue.

If anyone can provide assistance, I would greatly appreciate it. Thank you all for your support.

Answer №1

After struggling with some issues, I was able to resolve them on my own through trial and error. Pinia was not the problem.
The main issue I encountered was starting the project without TypeScript and attempting to integrate it later in "some file."

If you're looking to enable TypeScript, make sure to convert all your .js files to .ts
This step is unnecessary for .vue files.
Here are the various steps I took to ensure everything functions smoothly:

Utilize this tsconfig :

{
  "compilerOptions": {
    // Detailed compiler options here
  },
  "include": [
    // Include specific file paths here
  ],
  "exclude": [
    "node_modules"
  ]
}

Include shims-vue.d.ts in your main folder (/assets for example), even though its purpose may be unclear, it proved to be essential.

// Contents of shims-vue.d.ts

Remember to specify the language in component creation:

<script lang="ts">

Ensure to change your main.js or app.js to .ts and update webpack.config.js accordingly

.addEntry('app', './assets/app.ts')
.addAliases({
     '@app': path.resolve(__dirname, 'assets/')
})

Following these adjustments, expect to encounter several compile-time errors that require modifications in your code.

A common issue is failing to import .vue files resulting in a "module not found" error.

In cases like this, switch from:

import App from './App';

To:

import App from './App.vue';

If anyone has alternative practices, please share them so I can refine my approach accordingly.

Answer №2

Consider naming the defineStore function with a specific name as the first argument, followed by the options object as the second argument. This is similar to what you did with your authStore.

from:

export const useCountryStore = defineStore( {
    id: "country",
    state: () => ({
        countries: [],
        errors: []
    } as CountryState)
})

to:

export const useCountryStore = defineStore("country", {
    id: "country",
    state: () => ({
        countries: [],
        errors: []
    } as CountryState)
})

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

Encountering the "Vue warn: Error compiling template" issue in Laravel while utilizing the Dump function

I have a minor issue with my Blade template. When attempting to display the contents of a PHP array using dump(), I encounter an "Error compiling template" message from Vue. My Laravel version is 7.15. This problem persists even when I utilize the Blade di ...

Persisted state in Vuex fails to retain data after the page is refreshed

I recently added persisted state to my Vue application using the command npm install --save vuex-persistedstate. After that, I configured my Vuex store.js file in the following way: import Vue from 'vue' import Vuex from 'vuex' import ...

Ways to modify the access control to permit origin on a specific API URL in React

https://i.stack.imgur.com/tqQwO.png Is there a way to modify the access control allow origin for a URL API? I keep encountering error 500 whenever I try to load the page. After logging in, I included this code snippet: const options = { header ...

Issue with VueJS $set: Unable to create a new reactive property within an array of objects

Within my VueJS 2 component showcased below, I have succeeded in assigning the imgdata property to each question within the area.questions array. Although it appears to be functioning as expected - revealing values through the console.log, the challenge ...

The router-link feature in Vue.js is experiencing issues with functionality in the Firefox browser

Presenting the button component below: <button :class="classes" v-on="$listeners" v-bind="$attrs"> <template v-if="to"> <router-link :to="to" class="flex center-v"> <AqIcon :icon="icon" v-if="icon" /> ...

The Vue background container fails to display the image

I'm having trouble setting an image as the background for a div element. Despite my numerous attempts, I haven't been able to make it work. No results are displayed and there are no error messages to indicate what went wrong. I recently stumble ...

Why does Vue 3 template display 101 instead of 1 when incrementing the number from 0?

Vue.createApp({ data() { return { counter: 0 } }, template: '<div>{{counter++}}</div>' }).mount('#root') Ultimately, the code above displays the number 101 on the page. Any insights into why this is happ ...

Issue encountered in TypeScript: Property 'counter' is not found in the specified type '{}'.ts

Hey there, I'm currently facing an issue while trying to convert a working JavaScript example to TypeScript (tsx). The error message I keep encountering is: Property 'counter' does not exist on type '{}'.ts at several locations wh ...

Is it possible for an object to be undefined in NextJS Typescript even after using a guard

Hey there, I could really use some help with a React component I'm working on. This is one of my initial projects and I've encountered an issue involving fetching async data. Below is the current state of my solution: import { Component } from &q ...

Ionic table data is manipulated by the Vuex store manager

Code: https://github.com/cbsmerveguel/ionicblank Hey everyone, I'm diving into the world of vuejs and vuejs with ionic for the first time. I wanted to experiment with a master-detail view, where there is a table on the master page and the details of ...

Unknown custom element error in Laravel and Vuetify

I encountered errors in my Laravel project, specifically with custom elements like this. [Vue warn]: Unknown custom element: <v-app> - did you register the component correctly? For recursive components, make sure to provide the "name" option. found ...

Trouble with embedding video in the background using Next.js and Tailwind CSS

This is the code snippet for app/page.tsx: export default function Home() { return ( <> <main className='min-h-screen'> <video muted loop autoPlay className="fixed -top ...

Access-Control-Allow-Methods does not allow the use of Method PUT in the preflight response, as stated by Firebase Cloud Functions

I am facing an issue with my Firebase cloud function endpoint. I have a setup where it forwards PUT requests to another API endpoint. I have configured the following Access-Control-Allow- headers: // src/middlewares/enableCORS.ts export default function en ...

What steps can I take to avoid displaying repetitive error messages upon form submission in Vue.js?

I am experiencing an issue where error messages are being displayed multiple times when the form is submitted empty. How can I ensure that only a unique set of error messages is shown, rather than looping through and repeating them? Here's how it app ...

There is a chance that the object could be 'undefined' when attempting to add data to it

I created an object and a property called formTemplateValues. I am certain that this property exists, but I am getting an error message saying: "Object is possibly 'undefined'". It should not be undefined because I specifically created it. Why am ...

Utilizing a service within NestJS

I'm currently in the process of updating some older code and I have created a service that I want to inject into the constructor of a class. There are two key points to consider about this particular class. The first point is that it is instantiated b ...

The expression has been altered following verification. It previously read as 'model: 1777' but now states 'model: 2222'

I've been working on this HTML code that utilizes [(ngModel)] to update input values, and I want the Total, Subtotal, and Amount Paid fields to be automatically calculated when a change is made. However, I'm encountering some issues with this app ...

What is the best way to implement Angular translation for multiple values in a typescript file, while also incorporating parameters?

this.snackBar.open( `Only files of size less than ${this.fileSizeAllowed}KB are allowed`, this.translate.instant('USER_REG.close'), { panelClass: 'errorSnackbar', ...

The React DOM isn't updating even after the array property state has changed

This particular issue may be a common one for most, but I have exhausted all my options and that's why I am seeking help here. Within my React application, I have a functional component named App. The App component begins as follows: function App() ...

After the transition from Angular 8 to Angular 9, an issue arose with the node_modules/@zerohouse/router-tab/zerohouse-router-tab.d.ts file, as it was not declared

Error Image package.json { "name": "client", "version": "0.0.0", "license": "MIT", "scripts": { "ng": "ng", "serveapp": "ng serve ...