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.
How to break pinia store into individual files?
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/802 –
Vulgarian
It's moved to the discussion github.com/vuejs/pinia/discussions/1324 –
Bedfast
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()
}
});
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.
© 2022 - 2024 — McMap. All rights reserved.