i have array of products in state.allItems. (each product has id, title etc.) i want to change info about element by button. i send product's id.
think that i make something wrong in mutations. action:
UPDATE_PRODUCT({commit}, id){
const token = localStorage.getItem('token');
return axios.request({
url: '`{url}`',
method: 'put',
data: {id:id},
headers: { Authorization: `Bearer ${token}` }
})
.then((resp)=>{
commit('UPDATE_PRODUCT_IN_STATE', resp)
alert('Товар успешно изменен!')
console.log(resp)
return resp;
})
.catch((error)=>{
console.log(error)
return error;
})
},
mutation:
UPDATE_PRODUCT_IN_STATE: (state, id)=>{
state.allItems = state.allItems.map(i=>i.id===id)
},
CodePudding user response:
It is not easy to know what you try to achieve but here:
I guess your map method will return an array that looks like this: [false, false, true, false...]
It is because state.allItems.map(i => i.id === id)
will compare
every item in state.allItems
and return either true
or false
based on whether the current item id
matches the id
that is sent as parameter.
Check this out: https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Global_Objects/Array/map
CodePudding user response:
I'm guessing you're using vuex right now. If your "resp" is a new item what I suppose you're going to do is to replace the old item with the same id inside allItems with the new item "resp".
A simple way to archive this is through the array splice function.
The following should help you to reach your goal.
UPDATE_PRODUCT_IN_STATE: (state, resp) => {
const { id } = resp;
const toUpdateIndex = state.allItems.findIndex(el => el.id === id)
if(toUpdateIndex === -1) return state;
state.allItems.splice(toUpdateIndex,1,resp);
},