DEV Community

cn-2k
cn-2k

Posted on

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

Top comments (0)