Best practices for manipulating state on or immediately after read (getters) #696
-
I'm sitting down to write a basic global notifications store for message toasts. When the client sees a change in the state (via a subscription) the application should:
It's been a long time since I've done deeper front-end work with global state stores so I'm rusty on best practices, and I'm curious if patterns and practices have changed. In my head "retrieving a value" means getter, but since I want to manipulate the state when this occurs, I'm thinking action. I can put this logic in a component - call the getter to retrieve the value and then call the action to remove it from the internal state notifications array, but it kind of feels like business logic. Does this logic belong explicitly in the component? Or alternatively should I write a getNextNotification() action that shifts the item off the array, manipulating the state, and then returns the value? At first glance this encapsulates how I want the client to interact with the store better, but I haven't seen examples that return state values from actions, and if I remember correctly in something like vuex with more explicit commits this may not be recommended. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
There's a lot of ways to go about this, as far as best practices go you don't want to have side effects in a getter, so if you do need to have a side effect an action would be better. There's nothing wrong with returning some portion of the state at the same time as manipulating the store. Here's an example of one way to implement this: https://codesandbox.io/s/pinia-vue-3-notification-hrj9h Hope this generates some ideas 😄 At the end of the day it's whatever is going to suit your needs the most, making sure the end result is easy to read, simple to test & flexible enough to make changes later. |
Beta Was this translation helpful? Give feedback.
There's a lot of ways to go about this, as far as best practices go you don't want to have side effects in a getter, so if you do need to have a side effect an action would be better. There's nothing wrong with returning some portion of the state at the same time as manipulating the store.
Or you could just read and manipulate the store state directly which isn't a problem in Pinia like it was in Vuex, unless you want to be very explicit by only using actions which some prefer.
Having the business logic in the consuming component is a matter of preference, personally in this case only 1 component would be reading the notifications, so to me it makes sense to keep that logic within the com…