DEV Community

cn-2k
cn-2k

Posted on

9 1

Creating stores with pinia in Vue 3 + Typescript

Pinia is the new state management system for Vue and in this article I'll show two ways of use this amazing tool with Typescript and simple examples.

1 - Simple store with Typescript assertion

import { defineStore } from "pinia";
import type { MyInterface } from "@/types";

type RootState = {
  myState: MyInterface[];
};

const useMyStore = defineStore("franchiseStore", {
  state: () =>
    ({
      myState: [],
    } as RootState),
  actions: {
    setCurrentState(state: MyInterface[]) {
      this.myState = state
    },
  },
});

export default useMyStore;
Enter fullscreen mode Exit fullscreen mode

2 - Simple store with Typescript assertion and using Composition API

import { defineStore } from 'pinia';
import { ref } from 'vue';
import type { MyInterface } from '@/types'

export const useMyStore = defineStore('myStore', () => {

  const myState = ref<Array<MyInterface>>([]);

  function setCurrentState(state: MyInterface[]) {
    myState.value = state
  }

  return { myState, setCurrentState };
});

export default useMyStore;
Enter fullscreen mode Exit fullscreen mode

Do your career a big favor. Join DEV. (The website you're on right now)

It takes one minute, it's free, and is worth it for your career.

Get started

Community matters

Top comments (0)

Postgres on Neon - Get the Free Plan

No credit card required. The database you love, on a serverless platform designed to help you build faster.

Get Postgres on Neon

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay