Vuex setting variables in state from actions


  1. I am trying to populate a variable (onSale) in state but not able to .
    I am getting my data from a json file. what is wrong with my code ?

  2. A separate question is sometimes i see the word ‘context’ instead of ‘state’, what is needed for and when to use it ?

Thanks for help.

    state: {
       products: [],        
        onSale: [],
    },
   actions: {

        async fetchProducts({commit, state}) {
            axios.get('/src/assets/phones.json')
                .then(response => {
                    commit('setProducts', response.data) //      setProducts(state, products) {
                    // alert(response.data)
                })

            let allM = []
           await  state.products.map((d) => {
                for (let i = 0; i < Object.keys(d).length; i++) {
                    if (d["onSale"])
                        allM.push(d["onSale"])
                }
            })
            //alert(allM)
            //return new Promise((resolve, reject) => {
                commit('setOnSale1', allM)
                //    alert(allM)

            })


        },

  mutations: {
        setOnSale1(state, onSale) {
            state.onSale = onSale
        },
},

Source: Vue – Stack Overflow

November 27, 2021
Category : News
Tags: Vue.js | vuex

Leave a Reply

Your email address will not be published. Required fields are marked *

Sitemap | Terms | Privacy | Cookies | Advertising

Senior Software Developer

Creator of @LzoMedia I am a backend software developer based in London who likes beautiful code and has an adherence to standards & love's open-source.