Answer the question
In order to leave comments, you need to log in
How to get state in action?
How permissible is it directly in the action to access state.page
and increase the values by 1 in the same place? Perhaps it is better to do this through a mutation similar to setProducts()
? The truth is that there is no direct escape from the appeal. I can only make the value increase by 1 through mutation, right?
// state
const state = {
page: 1,
all: []
}
// getters
const getters = {}
// actions
const actions = {
getProducts ({ commit }, $state) {
axios.get('/api/products', {
params: {
page: state.page,
},
}).then(({ data }) => {
if (data.data.length) {
commit('setProducts', data.data)
state.page += 1
$state.loaded();
} else {
$state.complete();
}
});
}
}
// mutations
const mutations = {
setProducts (state, products) {
state.all.push(...products)
}
}
export default {
namespaced: true,
state,
getters,
actions,
mutations
}
Answer the question
In order to leave comments, you need to log in
You can read directly from the state, write - only through mutations. In addition, you need to take the current state from the context (1 argument), and not the object that is passed to the constructor:
const actions = {
getProducts({ commit, state, rootState }) {
if (state.page) doStuff() // чтение
commit('SET_PAGE', 2) // запись
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question