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

Merging Promises in Typescript

In summary, my question is whether using a union type inside and outside of generics creates a different type. As I develop an API server with Express and TypeScript, I have created a wrapper function to handle the return type formation. This wrapper fun ...

Problem encountered while directing to a component within Angular

Here is the overview of my directory structure: Directory Structure login.component.ts: import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormControl, FormGroup, Validators, ReactiveFormsModule } from '@angular/forms ...

Utilizing the power of d3.js within Angular 4

Currently, I have successfully implemented code to draw a polygon using the mouse in a normal JavaScript file. Now, I am looking to replicate the same functionality in my TypeScript file. Below is an excerpt from my d3.js file: //D3.JS VERSION 3 //------ ...

The Vuetify date-picker fails to display the final week of the month

My experience with Vuetify's v-date-picker revealed an issue where the last week of the month is not displayed on Android devices. The same problem occurred when using Google Chrome on a computer and zooming in. I attempted to replicate the issue, how ...

Encountered a problem with regular expressions in Angular 2 - a Module parse error due to an octal literal in strict mode

Greetings, I have encountered an issue with a regular expression in my environment.ts file. export const environment = { passwordPolicy: "^(?!.*(.)\1\1)(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,}.*$" }; Unfortunately, whe ...

Refining a Collection of Possible Options

If I have an array of type Maybe<int>[] and want to extract only the values that are not None, what is the most efficient approach while ensuring TypeScript recognizes the output as int[]? It seems like declaring the result type as int[] is the way ...

`express-validator version 4 is not functioning as expected`

Trying to implement input validation using express-validator v4.3.0 for my express routes, but despite following the documentation, I am unable to get it working correctly. It seems to not detect any errors and also gets stuck in the route. Could it be tha ...

Unrestricted Angular Audio Playback without CORS Restrictions

I am currently developing a web application using Angular4 that will include the feature of playing audio files. Unfortunately, I am facing an issue where I do not have control over the server serving the media files, and therefore cannot make any modifica ...

How can I resolve a bug in Nuxt2 when using TypeScript?

I need help with implementing code using Nuxt.js 2 option API with TypeScript. computed: { form: { get: () => this.value, set: (value) => this.$emit('input', value) } } Additionally, I am encountering the fo ...

Setting up Mailgun with TypeScript on Firebase Cloud Functions

Currently, I am working on a Cloud Function within Firebase to integrate with Mailgun for sending emails, following the guidelines provided in the Mailgun documentation. My challenge lies in implementing this functionality using TypeScript, as I have been ...

Ways to differentiate between the sources of two cold Observables (not just the possible data streams they may produce)

Situation: Within my Angular application, I am using publishReplay to store and replay specific Http requests. However, I encountered an issue where I need the cached observable source to update itself and create a new cached observable with publishReplay ...

Angular 2: Shared functions for universal component usage

I am working on an Angular 2 webpack project and I have come across a scenario where I have some functions that are repeated in multiple components. I want to find a way to centralize these functions in a "master" class or component so that they can be eas ...

Error TS2403: All variable declarations following the initial declaration must be of the same type in a React project

While developing my application using Reactjs, I encountered an error upon running it. The error message states: Subsequent variable declarations must have the same type. Variable 'WebGL2RenderingContext' must be of type '{ new (): WebGL2 ...

Error message is not shown by React Material UI OutlinedInput

Using React and material UI to show an outlined input. I can successfully display an error by setting the error prop to true, but I encountered a problem when trying to include a message using the helperText prop: <OutlinedInput margin="dense&quo ...

When I specify the type for the function parameter, an error occurs when I attempt to execute the function

When I assign a generic type to the function parameter and try to call the function, an error message pops up stating "This expression is not callable. Type unknown has no call signature." function a() { return 'abc' } function fun<T>(x: T ...

Angular's interactive checkboxes and dropdown menus provide a dynamic user experience

There is a global List array where data from an API is passed in the OnInit method. List: any; visibility:any; Status:any; ngOnInit(): void { let param = {...}; this.Service.getUser(param).subscribe(result => { this.List = result['response ...

Explore the possibilities of Vue by searching through an array of APIs in

As a newcomer to Vuejs, I am currently working on a web app that retrieves images from the Flickr API and stores them in an array. I want to implement a basic search functionality that allows users to filter images based on the keyword entered, but I am un ...

The data type 'boolean' cannot be assigned to the type 'StoryFnReactReturnType' in a React Storybook project using Typescript

I am currently working on setting up a Button component with Storybook in typescript. I am referencing The Documentation and using this specific example. Below is my Component and its story: components/Button.tsx: import {FC} from 'react'; exp ...

Retrieving information from an API with the help of Vue.js

I am encountering an issue while attempting to retrieve data from an API using Vue.js. Despite my efforts, I have been unsuccessful in achieving this goal. Here is the code snippet: <!DOCTYPE html> <html> <head> <title>V ...

Tips for fixing the error message "unable to access property 'property-name' of null"

I need assistance with retrieving data from a firebase database and storing it in an array using typescript. Below is the code snippet I am working with: export class ViewUserPage { public list = []; public ref = firebase.database().ref(); public ...