There are certain components in my application that do not need to store all their state globally. Let me provide you with two examples:
messages
component: User messages are fetched and stored locally because they are only required for the current component's usage. However, if there is an error fetching the messages from the API, then the error needs to be dispatched to the global state (vuex).buy
component: The 'recent buys' information is fetched and stored locally, but the 'money' data should be dispatched to the global state. In case of an error while fetching recent buys, the error should also be dispatched.
I am currently trying to figure out how best to structure this setup and could use some assistance. I have a directory named services
which contains API calls. Let's take the buy service as an example:
/services/buy.js:
// Code here to dispatch money state
// Code here to dispatch 'last activity' state
Vue.$http.get('/buy', credentials)
.then((response) => {
// Return recent buys
})
.catch((error) => {
// code here to dispatch error state
});
There are interdependencies between these services as well. For instance, after a successful purchase, a new message needs to be sent using /services/newMessage.js.
But where and how should I organize all of this logic? Let's consider the buy
component as an example. Here are a few options:
#1: This corresponds to the above code
- The buy component imports the buy service and executes it using
newBuy()
- The service dispatches the money to the global store and retrieves recent buys, returning them
- In the component, the returned value from the service updates the local store
- The component also includes logic: upon successful return, it triggers the message service to send a new message using
sendMessage()
#2: The main difference from #1 is that the logic resides within the service
- The component imports the buy service and calls it using
newBuy()
- The service dispatches the money to the global store and imports the message service
- The message service sends a new message using
sendMessage()
- Returning to the buy service, recent buys are fetched and returned
- The component now updates the local store with the retrieved value
#3: This differs from the aforementioned steps by including all Vuex-related actions in a dedicated actions.js file, thereby ensuring clear separation between global and local state updates
- The component imports the buy service and executes it using
newBuy()
- The service imports ./store/actions.js and invokes the
updateMoney()
service to update the money in the global state - It can proceed with the steps outlined in #1 or #2
I would appreciate any guidance on how to effectively merge components that utilize both global and local states. Would any of the above three approaches be suitable for achieving this goal?