O
O
Oleg Pravdin2020-09-14 11:20:51
Vue.js
Oleg Pravdin, 2020-09-14 11:20:51

How to properly separate component, storage and API requests?

Good afternoon. My application uses a Vuex store and a separate set of methods to query the view API

export default {
    get() {return axios.get(....)},
}

When developing applications using the API, I take the following approach:
1) When data is used in one component or within child components, I directly import the method to make a request to the API, call it inside mounted/created and store the data in the component's data
2) When the data is used globally, dispatch is executed in created (where the API request is executed), then through the mutator the data gets into the storage and is used in the application through computed.

Questions:
1) Am I abstracting enough from working with requests in paragraph 1 (do I need some kind of layer). In particular, I saw an approach with entering all API requests into actions, some of which do not affect the state, but simply return the result of the request to the API
2) Are there any fundamental flaws in my approach? Am I doing something wrong?
3) Where to write error handler in API requests?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey delphinpro, 2020-09-14
@delphinpro

2. Reverse opinion Alex :
On the contrary, I prefer to store all the data in the store. Components only have local variables.
All requests to the API are located in actions and, accordingly, the data is immediately placed in the store.
Accessing the store only through getters. The necessary actions and getters are mapped into the component.
3. It is convenient to intercept errors in Axios interceptors. We configure the option validateStatusas needed and catch everything in one place.

A
Alex, 2020-09-14
@Kozack Vue.js

  1. Whether enough depends on your case. Let's say there is a possibility that you will need to change one API server to another? Or, in principle, change the API scheme?
  2. As for global data. It may be different here. I adhere to the following approach: each component must itself load the data it needs. And in Vuex, store less. There is no clear boundary here. For example, you can take out all the operations for working with api in Vuex and use it as a cache store. But is it necessary? Wouldn't it be better to make caching the honor of the module by calling the api? Or, for example, you need to store a history of the user's recent actions. For this, for example, you can use the IndexedDB API.
  3. As for me, in the place where the call is made. That is, a component that requests some data (through any number of abstractions) must receive either data or an error report and decide for itself how to process it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question