Middle
Is it possible to make an API call in a computed property?
sobes.tech AI
Answer from AI
In computed properties (for example, in Vue.js), it is not recommended to perform asynchronous operations such as API calls. Computed properties are intended for synchronous calculation of values based on reactive data.
If you need to fetch data from an API, it is better to use component lifecycle methods (such as mounted) or watch to monitor changes and invoke asynchronous functions.
Example of the correct approach:
export default {
data() {
return {
apiData: null
}
},
mounted() {
this.fetchData();
},
methods: {
async fetchData() {
const response = await fetch('https://api.example.com/data');
this.apiData = await response.json();
}
},
computed: {
processedData() {
// Here, only synchronous processing of apiData
return this.apiData ? this.apiData.map(item => item.value) : [];
}
}
}
Thus, computed remains a pure function without side effects.