Storing Pinia state with useLocalStorage in Typescript annotations

Within my Pinia-based store, I have state with the following properties:

import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useLoginStore = defineStore('login', () => {
  // State
  const isAuthenticated = useLocalStorage('isAuthenticated', false)
  const user = ref<{ name: string; email: string } | null>(null)
  const accessToken = ref<string | null>(null);

  // Actions
  const login = (userData: { name: string; email: string }, token: string) => {
    user.value = userData
    isAuthenticated.value = true
    accessToken.value = token
  }

  const logout = () => {
    user.value = null
    isAuthenticated.value = false
    accessToken.value = null;
  }

  return {
    isAuthenticated,
    user,
    accessToken,
    login,
    logout,
  }
})

Referring to the VueUse documentation, I made adjustments to the initial value as per its simple type inference, however, I am struggling to explicitly specify more complex type annotations:

...
// State
const isAuthenticated = useLocalStorage('isAuthenticated', false)
const user = ???
const accessToken = ???
...

UPDATE: included the complete Pinia store for better understanding

Answer №1

While the solution may seem obvious, I am still in the early stages of learning TypeScript type annotation syntax. Here is a helpful snippet that could potentially save someone some valuable time:

  const isLoggedIn = useLocalStorage('isLoggedIn', false)
  const userDetail = useLocalStorage<{ fullName: string; email: string } | null>('userDetail', null)
  const authToken = useLocalStorage<string | null>('authToken',null)

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

I'm puzzled as to why there is a blank space in the false element statements

Hey there! I'm noticing a blank space on the page, and when I inspect it, I see this bindings={ "ng-reflect-ng-if": "false" }. It seems like I am getting some blank cards displayed. Here is an image showing what I mean: https://i. ...

Difficulty encountered when attempting to create a lambda function in TypeScript

I'm having trouble understanding the following lambda function definition in TypeScript. It could be a beginner question. type P = { id: string } type F = <T>(x: T) => string const f: F = (x: P) => x.id f({ id: 'abc' } However, ...

When a user clicks on empty space in Angular 2, the page will automatically redirect

When I receive a response from the server, I want to redirect to another page. However, this process takes around 60 seconds, so in the meantime, I want to display a spinner. Once the response is received, I should be redirected to the new page. Sounds sim ...

Adding an interface for an object containing multiple objects requires defining the structure and behavior

I'm in the process of designing an interface for my object. Here is the data structure of the object: { "isLoaded": true, "items": { "0": { "name": "Mark", "age": "40" }, "1": { "name": " ...

Animations are failing to run within a Bootstrap card when using Vue rendering

I have utilized Bootstrap cards to display pricing information in my project. I implemented a collapse feature for half of the card when the screen size is equal to mobile width. While using vanilla Bootstrap, the animation worked seamlessly with the col ...

Having trouble with ngFor not iterating through child properties?

Having trouble with implementing angular 2 ngFor Defined model: export class PaginationPage<T> { content: Array<T>; } In component: page: PaginationPage<Blog>; blogs: Array<Blog>; ... this.blogs = page.content; In ...

Error TS7027: Unreachable code was identified in TypeScript

sortArrayDate(arrayToSort, arrayDateKey, order) { if (order === 'ascending') { arrayToSort.sort(function(a, b){ if (a[arrayDateKey] === '' || a[arrayDateKey] === null) { return 1; } if (b[arra ...

What are the steps for transforming an HTML page into a fully-fledged Vue or React project?

I have been customizing a dashboard using AdminLTE 3, removing unnecessary parts and modifying the HTML and CSS files. However, I now need to convert this project into either a Vue or React project. Currently, all I require is an index.html file with a bla ...

Testing server sent events with Angular solely using Karma-Jasmine

I am currently developing a web application using Angular for the frontend and Python for the backend. My implementation involves utilizing server-sent events (SSE) to stream data from the server to the user interface. While everything is functioning prope ...

Determine when the scrollbar of a DIV has reached the bottom using Vue.js

Just starting out with Vuejs and I could use some guidance. Can anyone please advise on how to trigger a message when a div in Datatable vuejs reaches the bottom of its page? Any help would be greatly appreciated. https://i.sstatic.net/jKfRT.jpg https://i ...

What imports are needed for utilizing Rx.Observable in Angular 6?

My goal is to incorporate the following code snippet: var map = new google.maps.Map(document.getElementById('map'), { zoom: 4, center: { lat: -25.363, lng: 131.044 } }); var source = Rx.Observable.fromEventPattern( function (han ...

Why isn't the table in the select query updating after an insert query is executed in Express?

Seeking assistance! Currently, I am delving into express and typescript. I have encountered an issue where the table from a select query does not update after an insert query when rendering a view. Strangely, the data in the table remains unchanged (showin ...

What causes the Babel JSON configuration error to appear in my project?

I'm currently working on a React website, utilizing TSX instead of JSX. In my setup, I am using webpack and Babel. However, I have encountered an error while running the webpack-dev-server. ERROR in ./src/index.tsx Module build failed (from ./node_mo ...

Autoformatting files with ESLint on save

I'm encountering an issue where Visual Studio Code is saving my file in violation of the rules specified in my eslint configuration when using eslint and prettier for formatting. module.exports = { env: { browser: true, es2022: true, nod ...

Typescript: Determine when a property should be included depending on the value of another property

Having some difficulty with Typescript and React. Specifically, I am trying to enforce a type requirement for the interface Car where the property colorId is only required if the carColor is set to 'blue'. Otherwise, it should not be included in ...

Angular TypeScript Directive Link function not being executed

I've been working on implementing a Role-Based-Access-Control system in my application. The allowed resources are loaded from the server after login, and I was able to verify this using raw JavaScript code. angular.module('app').directive(& ...

Handling Errors in RxJS: A guide to propagating errors from observables

I recently started learning RxJS and am currently focusing on observables and subjects. I have a basic login code that is split into two separate files: a) auth.service.ts and b) login.component.ts Below is the content of login.component.ts: public login( ...

I'm having trouble getting Remix.run and Chart.js to cooperate, can anyone offer some guidance?

I've encountered a challenge with Remix.run and chart.js (react-chartjs-2) when attempting to display the chart. I followed the documentation and installed the necessary dependencies: react-chartjs-2 and chart.js. Here's the snippet from my pac ...

Having trouble simulating a service using nuxt and jest

In my project, I have created a component named External.vue. This component includes a button with props and triggers a Google Analytics event whenever it is clicked. <template> <div> <button ref="ctaButtonExternalElement&q ...

Using async/await does not execute in the same manner as forEach loop

Here is a code snippet that I have been working with. It is set up to run 'one' and then 'two' in that specific order. The original code listed below is functioning correctly: (async () => { await runit('one').then(res ...