My goal is to update my component state with data retrieved from an API using a getter in the store.
Within the mounted()
lifecycle hook, I call the getProducts()
getter which is defined as:
export const getters = {
async getProducts() {
axios.get('/api/products')
.then(res => {
var data = res.data
commit('setProducts', data)
})
.catch(err => console.log(err));
}
}
The getProducts()
getter attempts to execute a mutation named setProducts()
, which is defined as follows:
export const mutations = {
setProducts(state, data) {
state.products = data
}
}
However, upon running this code, I encounter the error ReferenceError: commit is not defined in the console.
The issue seems to be related to triggering the mutation, and despite extensive research over two days, I have been unable to find a solution.
I attempted replacing commit('setProducts', data)
with:
this.setProducts(data)
setProducts(data)
Unfortunately, all of these attempts resulted in the error "TypeError: Cannot read properties of undefined (reading 'setProducts')".