1
1
100R2019-08-26 23:47:32
Vue.js
100R, 2019-08-26 23:47:32

How to get state in action?

How permissible is it directly in the action to access state.pageand 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

2 answer(s)
D
Daniil Bratukhin, 2019-08-27
@100R

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) // запись
  }
}

A
Andrey Suha, 2019-08-27
@andreysuha

Changes state value only in mutation, you can get it anywhere

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question