Image of the Pinia logo made by VueSchool.io

Creating a store with Vue 3, Pinia and TypeScript

State management lets you run a faster application. For a while now, Pinia has replaced Vuex in Vue applications. And with Pinia, it’s time to embrace the Composition API, even within the stores.

Pinia is the recommended state management plugin in Vue applications.

Though you can use it with the “Option API” way, if you are using TypeScript, go for the “Composition API” way. Yes, even within the stores, you can use the setup pattern.

With JavaScript, you would have, for example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
import { ref } from 'vue';
import { defineStore } from 'pinia';
import useSampleData from '@/composables/useSampleData';

const { categoriesData } = useSampleData();

export const useCategoryStore = defineStore('CategoryStore', {
  state: {
    categories = ref(categoriesData);
  },
  getters: {
    getCategoryById = (categoryId) => {
      const match = this.categories.value.find(
        (category: Category) => category.id === categoryId
      );
      if (match === undefined) return {};

      return match;
    }
  }
});

With TypeScript, it becomes:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import { ref } from "vue";
import { defineStore } from "pinia";
import useSampleData from "@/composables/useSampleData";
import type Category from "@/types/Category";

const { categoriesData } = useSampleData();

export const useCategoryStore = defineStore("CategoryStore", () => {
  //STATE
  const categories = ref(categoriesData);

  //GETTERS
  const getCategoryById = (categoryId: string | undefined): Category => {
    const match = categories.value.find(
      (category: Category) => category.id === categoryId
    );
    if (match === undefined) return {};

    return match;
  };

  return { categories, getCategoryById };
});

The arrow function you see after the name of the store uses the function definition with the setup pattern.

Special thanks to :

License GPLv3 | Terms
Built with Hugo
Theme Stack designed by Jimmy