How to break pinia store into individual files?
Asked Answered
I

2

7

I am using pinia to manage state into my Vue3 app. There has been thorough discussion here to break pinia store into individual files like state, getters, actions. But I am looking for a more 'stable' and 'elegant' solution to break the pinia store into individual files.

Inference answered 7/5, 2022 at 15:36 Comment(3)
This isn't recommended because this will disable type inference for the store. Even if you don't use TS, it's useful in IDE. The habit to break them comes from Redux that suffers from boilerplate problem. This isn't the case here.Stratocracy
There is a discussion here: github.com/vuejs/pinia/issues/802Vulgarian
It's moved to the discussion github.com/vuejs/pinia/discussions/1324Bedfast
E
0

If you look at the discussion, there's one answer with an interesting suggestion

Using a setup store to split the store into smaller functions that are composables

This may look something like the following. It works perfectly fine with the IDE and behaves the exact same way it does as if you put everything into one file.

You could even break down the files in more detail, e.g. special actions for interacting with the server, or for changing a specific state.

File structure

myStore
 |- index.ts
 |- state.ts
 |- getters.ts
 |- actions.ts

state.ts

// You need to keep the actual state outside the function to make it global
const someState = ref<number[]>();
const isInitialized = ref<boolean>(false);

export function useState() {
  async function initializeStore() {
    // init
  }

  return {
    someState,
    isInitialized,
    initializeStore
  }
}

getters.ts and/or actions.ts

export function useGetters() {
  const { someState } = useState();

  const entriesAboveZero = computed(() => /* */);
  function getEntriesBetween(low: number, high: number) { /* */ }

  return {
    entriesAboveZero,
    getEntriesBetween
  }
}

index.ts

export const useMyStore = defineStore('myStore', () => {
  return {
    ...useState(),
    ...useGetters(),
    ...useActions()
  }
});
Erg answered 21/4 at 15:3 Comment(0)
T
0

I would challenge rather the reason to split a Pinia store into multiple files. Why not multiple stores? Seams to me far more structured by concerns.

Trichina answered 15/6 at 8:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.