[Vuejs]-Adding result of Axios call to State

0👍

This is a little approach to your goal:

You can access with state.yourStateNameVariable or better make a getter and commit to get/set value from that state.

Observations:
[types.ADD_TO_CART] is not a good name for commit, maybe addToCart and removeFromCart?

You dont need to save in items your response from axios, you can directly after resolve send to all state with state.all = yourdata or better, add mutation

setAllData({ state }, data){
    state.all = data
}

I do not fixed all your code but here you are an approach:

import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'
import * as types from './mutation-types'

Vue.use(Vuex)

const debug = process.env.NODE_ENV !== 'production'

export default new Vuex.Store({
state:{
    added: [],
  all: [
    {
      id: 'cc919e21-ae5b-5e1f-d023-c40ee669520c',
      name: 'COBOL 101 vintage',
      description: 'Learn COBOL with this vintage programming book',
      price: 399
    },
    {
      id: 'bcd755a6-9a19-94e1-0a5d-426c0303454f',
      name: 'Sharp C2719 curved TV',
      description: 'Watch TV like never before with the brand new curved screen technology',
      price: 1995
    },
    {
      id: '727026b7-7f2f-c5a0-ace9-cc227e686b8e',
      name: 'Remmington X mechanical keyboard',
      description: 'Excellent for gaming and typing, this Remmington X keyboard ' +
        'features tactile, clicky switches for speed and accuracy',
      price: 595
    }
  ]
},
getters: {
 allProducts: state => state.all, // would need action/mutation if data fetched async
    getNumberOfProducts: state => (state.all) ? state.all.length : 0,
    cartProducts: state => {
        return state.added.map(({ id, quantity }) => {
            const product = state.all.find(p => p.id === id)

            return {
                name: product.name,
                price: product.price,
                quantity
            }
        })
    }
},
mutations: {
setAllData({ state }, data){
    state.all = data
},
 [types.ADD_TO_CART] ({ state }, id) {
        const record = state.added.find(p => p.id === id)

        if (!record) {
          state.added.push({
            id,
            quantity: 1
          })
        } else {
          record.quantity++
        }
      },
    [types.REMOVE_FROM_CART] ({ state }, id) {
        const record = state.added.find(p => p.id === id)

        if (!record) {
          state.added.pop({
            id,
            quantity: 1
          })
        } else {
          record.quantity--
        }
      }
},
actions:{
  loadItems({getters, commit}, somethingYouReceive) {

    // Init variables
    var self = this
    var app_id = "adsfasfasgag";
    var app_key = "agasdgagasgasg";
    this.items = []
    axios.get(
      "https://api.airtable.com/v0/"+app_id+"/Products",
      { 
        headers: { Authorization: "Bearer "+app_key } 
      }
    ).then(function(response){
      commit('setAllData',response.data.records.map((item)=>{
        return {
            id: item.id,
            ...item.fields
        }
      })
    }).catch(function(error){
      console.log(error)
    })
  },
   addToCart({ commit }, product){
        commit(types.ADD_TO_CART, {
            id: product.id
        })
    },
    removeFromCart({ commit }, product){
        commit(types.REMOVE_FROM_CART, {
            id: product.id
        })
    }
}
})

Leave a comment