DEV Community

Matthias Hryniszak
Matthias Hryniszak

Posted on

nano-pinia

One of the best qualities of Pinia is that it is actually a way to properly implement the singleton pattern. You define it as a function that always returns the same value.

I thought, since Vue already exposes the reactivity system as a separate package, can I implement singletons just like Pinia does - just without Pinia? What if I chose to only use the composition API?

function defineSingleton(cb) {
  const state = cb()
  return () => state
}
Enter fullscreen mode Exit fullscreen mode

That's it - nano-pinia in 4 lines or less :).

You use it just like you would use Pinia:

const useStore = defineSingleton(() => {
  const x = ref(1)
  const y = ref(2)
  const sum = computed(() => x.value + y.value)

  function incY() {
    y.value++
  }

  return { x, incY, sum }
})

// use the store instance directly
const s1 = useStore()
s1.x.value = 5
// or destructure the content
const { incY, sum } = useStore()
incY()

// it doesn't matter - it's a singleton
console.log(sum.value) // outputs: 8
Enter fullscreen mode Exit fullscreen mode

I think it's cool that you can do that with so little effort :) And it's a nice example of how to use closures - but who cares, right?

Top comments (0)