N
N
Nikolay Semenov2017-04-04 16:15:11
Vue.js
Nikolay Semenov, 2017-04-04 16:15:11

Why aren't all fields written to an object in an array?

Hi others!!
There is such a cart state file

import shop from '../../api/shop'
import * as types from '../mutation-types'

// initial state
// shape: [{ id, quantity, title, price }]
const state = {
    added: [],
    checkoutStatus: null,
}

// getters
const getters = {
    checkoutStatus: state => state.checkoutStatus
}

// actions
const actions = {
    checkout ({ commit, state }, products) {
        const savedCartItems = [...state.added]
        commit(types.CHECKOUT_REQUEST)
        shop.buyProducts(
            products,
            () => commit(types.CHECKOUT_SUCCESS),
            () => commit(types.CHECKOUT_FAILURE, { savedCartItems })
        )
    }
}

// mutations
const mutations = {
    [types.ADD_TO_CART] (state, { id, price }) {
        state.lastCheckout = null
        const record = state.added.find(p => p.id === id)
        if (!record) {
            state.added.push({
                id,
                price,
                quantity: 1
            })
        } else {
            record.quantity++
        }
    },

    [types.REMOVE_FROM_CART] (state, { id }) {
        state.lastCheckout = null
        const record = state.added.find(p => p.id === id)
        if (typeof record == 'object')
            var index = state.added.findIndex(p => p.id === id)
            if (state.added[index].quantity == 1) {
                state.added.splice(index, 1)
            } else {
                record.quantity--;
            }

    },

    [types.CHECKOUT_REQUEST] (state) {
        // clear cart
        state.added = []
        state.checkoutStatus = null
    },

    [types.CHECKOUT_SUCCESS] (state) {
        state.checkoutStatus = 'successful'
    },

    [types.CHECKOUT_FAILURE] (state, { savedCartItems }) {
        // rollback to the cart saved before sending the request
        state.added = savedCartItems
        state.checkoutStatus = 'failed'
    }
}

export default {
    state,
    getters,
    actions,
    mutations
}

why in the added array only objects with properties 'id' and 'quantity' are stored. I try to write 'price', I output the array to the console, but it is not defined? Guys help what is wrong.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question