Should I put business logic in stores? #2346
Replies: 1 comment
-
I see Pinia stores as a Reactive Service. Let's remove Pinia from the equation for a sec, how would we manage the state out of Vue components? With the reactive() object and using an instance of a class (the service): class AuthenticationService {
public isAuthenticated: boolean = false
public user: AuthenticatedUser | null = null
public login(email: string, password: string): Promise<void> {
// API call
this.isAuthenticated = true
this.user = data.value
}
}
const authenticationService = new AuthenticationService()
export const useAuthenticationService = () => reactive(authenticationService) So, translating that logic into Pinia, the Pinia store actions represent the methods of a service class... For me, using pinia stores as services have worked good enough, But of course, you can always have a services directory with services classes, and instantiate/call them from the pinia stores. I use mostly NestJS on the backend (sometimes use Nuxt as backend as well), and there we have modules, controllers, services. From ChatGPT:
// Pinia Store
import { defineStore } from 'pinia';
export const useCounterStore = defineStore('counter', {
state: () => ({
count: 0,
}),
actions: {
increment() {
this.count++;
},
},
});
// Service Class
export class CounterService {
incrementCounter(count) {
// Perform some business logic
return count + 1;
}
}
// Pinia Store
import { defineStore } from 'pinia';
import { CounterService } from '@/services/counterService';
export const useCounterStore = defineStore('counter', {
state: () => ({
count: 0,
}),
actions: {
async increment() {
const service = new CounterService();
this.count = await service.incrementCounter(this.count);
},
},
});
|
Beta Was this translation helpful? Give feedback.
-
I'm seeing 2 possible approaches here:
I'm using Nuxt 3 by the way, if that's a factor.
Suppose I have a collection of To Do tasks that get stored inside
useToDoStore
.When I add a new
To Do
to the store, let's say there's a little bit of business logic (for simplicity, let's say we're not communicating with an API for now):userId
of the To Do author existsLet's say there are multiple places in the app where we can add a new To Do.
I can see decoupling the business logic from the Pinia store as a merit if I decide to use a different state management library in the future, I guess? But at the same time the flow of data is easier to follow if the business logic is also kept inside the Pinia store. Is there perhaps a longer explanation for why the docs say that Actions are the perfect place to define business logic?
Beta Was this translation helpful? Give feedback.
All reactions