Import Pinia Store Into Other Store
Pinia makes state management within Vue apps a breeze to work with.
A common problem I run into is needing to access state from a different store. This can be solved using Pinia's composition syntax rather than the option syntax.
ts
// store/count.js
import { ref } from 'vue'
import { defineStore } from 'pinia'
export const useCountStore = defineStore('count-store', () => {
  const count = ref(0)
  function increaseCount() {
    count = count + 1
  }
  return { count, increaseCount }
})They can now be imported and used within other Pinia stores like so:
ts
// store/api.js
import { ref } from 'vue'
import { defineStore, storeToRefs } from 'pinia'
import { useCountStore } from './count'
export const useApiStore = defineStore('api-store', () => {
  const countStore = useCountStore()
  const { count } = storeToRefs(countStore)
  const { increaseCount } = countStore
  function displayCount() {
    console.log(count)
  }
  function increment() {
    increaseCount()
  }
  return { displayCount, increment }
})Stay Updated
Get notified about new posts and updates. No spam, unsubscribe anytime.
Comments
Share your thoughts and feedback using GitHub comments.