Nuxt.js store - update object in store object - throw Error: [vuex] do not mutate vuex store state outside mutation handlers - vue.js

in my Nuxt.js app
my store object is:
export const state = () => ({
curEditRP: {
attributes:{
name:"",
spouse: {
type: "", // wife/husband
name: ""
}
}
})
to update the attributes of curEditRP i wrote mutations function that called setCurEditRPAttrState:
export const mutations = {
setCurEditRPAttrState(state, payload) {
state.curEditRP.attributes[payload.attr] = payload.value;
},
}
from template i used it:
this.$store.commit("setCurEditRPAttrState", {
value: value,
attr: attributeName,
});
In a name update it works great
But in a spouse update it throws an error
Error: [vuex] do not mutate vuex store state outside mutation handlers
examples of values:
name (works great):
this.$store.commit("setCurEditRPAttrState", {
value: "Peter",
attr: "name",
});
spouse (throws an error):
this.$store.commit("setCurEditRPAttrState", {
value: { type:"wife",name:"S" },
attr: "spouse",
});
clarification: value is v-model variable

Bs"d, I find the solution.
in update object or array of object i need itarate over object properties and update each one individually
setCurEditRPAttrState(state, payload) {
if(typeof(payload.value) == 'object') {
let stateAttribute = state.curEditRP.attributes[payload.attr];
if(Array.isArray(payload.value)) {
let stateArrLen = stateAttribute.length;
let valuelen = payload.value.length;
while(stateArrLen > valuelen) {
stateAttribute.pop();
stateArrLen --;
}
for (let index = 0; index < payload.value.length; index++) {
const element = payload.value[index];
if(stateAttribute.length < index + 1) stateAttribute.push({});
Object.keys(element).forEach( key => {
Vue.set(stateAttribute[index], key, element[key])
})
}
}
else {
Object.keys(payload.value).forEach( key => {
Vue.set(stateAttribute, key, payload.value[key])
})
}
}
else {
state.curEditRP.attributes[payload.attr] = payload.value;
}
},

Related

Nuxt Store - CanĀ“t get all values in commit

In Vuex i try to send some values to a store, like this.
getStorage(
{ commit },
name: String | undefined = undefined,
objectA: ObjectA | undefined = undefined,
objectB: ObjectB | undefined = undefined
) {
if (selectedItinerary) {
commit('setA', objectA, objectB)
} else if (name) {
commit('setB', name)
}
},
The problem: Only get name value, objectA and objectB return undefinied.
So: Somebody say what's wrong? Maybe can only send one param?
UPDATE 1
Calling dispatch
this.$store.dispatch('business/getLocalStorage', {
name: this.name,
})
Store
getLocalStorage({ commit }, item) {
if (item.name) {
commit('setLocalStorageItinerary', item.name)
}
}
setLocalStorageItinerary(state, { name }: { name: string }) {
if (name) {
const itinerary = new LocalStorage()
itinerary.name = name
state.itinerary = itinerary
}
},
Assuming getStorage is an action, which receive the Vuex context as the first argument and a payload as the second, just wrap your values up inside an object before passing it as the payload.
eg.
somewhere in your app...
let payload = {
name: someValue,
objectA: someObject,
objectB: someOtherObject
}
this.$store.dispatch('getStorage', payload)
actions.js
getStorage({ commit }, payload) {
if (selectedItinerary) {
commit('setA', payload.objectA, payload.objectB)
} else if (payload.name) {
commit('setB', payload.name)
}
}
It isn't clear from your example where selectedItinerary is defined, but I think you get the gist from the above.

Delete item from pinia state

I am new to vue and I have just started using pinia. I wanna delete an item from array but it does not work
here is my store
import {defineStore} from 'pinia'
export interface ObjectDto {
input: string,
}
interface ObjectDtoInterface {
objects: Array<ObjectDto>
}
export const useSearchHistoryStore = defineStore('objectsStore', {
state: (): ObjectDtoInterface => {
return {
objects: [] as ObjectDto[]
}
},
actions: {
add(dto: ObjectDto) {
if (this.objects
.filter(shd => dto.input === shd.input)
.length === 0) {
this.objects.unshift(dto)
}
},
delete(obj: ObjectDto) {
this.objects = this.objects.filter(e => !(e.input === obj.input))
}
}
})
and here is the function from different .ts file
function delete(obj: ObjectDto) {
objectsStore.delete(obj)
}
add action works perfect, it adds item to the state but when I try to delete an item, nothing happens. The data I pass to delete method is 100% good because I checked this many times
Filter does not mutate the original object, you need to reasing
delete(obj: ObjectDto) {
this.objects = this.objects.filter(e => !(e.input === obj.input))
}
more info https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

TypeError: Cannot read properties of undefined (reading 'products')

I am trying to get products, then check if the product pId is in an array, and filter if it is.
I get an error when i soft refresh of 'TypeError: Cannot read properties of undefined' (reading 'products'), almost like my 'this.products' isnt populated yet when computed is trying to get the data. Tried adding some if statements to check data is there but no luck.
<script>
export default {
data() {
return {
popular_products: [],
products: [],
}
},
computed: {
bestsellers() {
const keywords = this.popular_products
let array = []
for (var index = 0; index < keywords.length; index++) {
const keyword = this.products.data.products.product.filter(
(product) => product.pId == keywords[index].ProductNumber
)
array = array.concat(keyword)
}
return array
},
},
mounted() {
axios
.get(
'https://myurl/admin/api/collections/get/popularproducts?token=account-9306f9192049d3c442e565f2de5372'
)
.then((response) => (this.popular_products = response.data.entries))
axios
.get('https://myurl/products.json')
.then((response) => (this.products = response))
},
}
</script>
The problem is with this line:
let keyword = this.products.data.products.product.filter(product => product.pId == keywords[index].ProductNumber);
more specific with this read: data.products.
You see, computed property bestsellers is evaluated before your axios calls are finished.
Because of that, Vue can't find products in data because your this.products doesn't have data key.
The best solution would be to change this assignment:
- .then(response => (this.products = response)); // delete this line
+ .then(response => (this.products = response.data.products)); // add this line
Update After comment.
if (this.products.product) {
return this.products.product.filter(...)
} else {
return []
}

getters not reactive in vuex

I have following store defined:
state: () => ({
infoPackCreationData: null,
infoPackCreationTab: null,
}),
getters: {
infoPackImage(state: any) {
return state.infoPackCreationTab && state.infoPackCreationTab.infopackContents
? state.infoPackCreationTab.infopackContents.filter((item: any) => item.type === "IMAGE")
: [];
}
},
mutations: {
setImageData(state:any, infopackImageData: any) {
state.infoPackCreationTab.infopackContents.filter((item: any) => {if(item.type === "IMAGE")
item = infopackImageData
console.log(item , 'this is items');
return item})
}
},
actions: {
setImageData(context: any, payload: any) {
context.commit('setImageData', payload)
}
}
and in my component I am using the computed to get the imageList:
computed: {
...mapGetters("creationStore", ["infoPackImage"]),
imageList: {
get() {
return this.infoPackImage ?? [];
},
set(value) {
this.$store.dispatch('creationStore/setImageData', value);
}
}
},
The problem is I want to edit a value of the imageList by index using draggable libarary,
but imageList does not act reactive and it just move the image and not showing the other image in the previous index:
async imageChange(e) {
this.loading = true
let newIndex = e.moved.newIndex;
let prevOrder = this.imageList[newIndex - 1]?.order ?? 0
let nextOrder = this.imageList[newIndex + 1]?.order ?? 0
const changeImageOrder = new InfopackImageService();
try {
return await changeImageOrder.putImageApi(this.$route.params.infopackId,
this.$route.params.tabId,
e.moved.element.id, {
title: e.moved.element.title,
infopackAssetRef: e.moved.element.infopackAssetRef,
order: nextOrder,
previousOrder: prevOrder,
}).then((res) => {
let image = {}
let infopackAsset = e.moved.element.infopackAsset
image = {...res, infopackAsset};
Vue.set(this.imageList, newIndex , image)
this.loading = false
return this.imageList
});
} catch (e) {
console.log(e, 'this is put error for tab change')
}
},
Array.prototype.filter doesn't modify an array in-place, it returns a new array. So this mutation isn't ever changing any state:
mutations: {
setImageData(state:any, infopackImageData: any) {
state.infoPackCreationTab.infopackContents.filter((item: any) => {if(item.type === "IMAGE")
item = infopackImageData
console.log(item , 'this is items');
return item})
}
},
So, if you intend to change state.infoPackCreationTab.infopackContents, you'll need to assign the result of filter():
mutations: {
setImageData(state:any, infopackImageData: any) {
state.infoPackCreationTab.infopackContents = state.infoPackCreationTab.infopackContents.filter(...)
However, since state.infoPackCreationTab did not have an infopackContents property during initialization, it will not be reactive unless you use Vue.set() or just replace the whole infoPackCreationTab object with a new one (see: Vuex on reactive mutations):
mutations: {
setImageData(state:any, infopackImageData: any) {
state.infoPackCreationTab = {
...state.infoPackCreationTab,
infopackContents: state.infoPackCreationTab.infopackContents.filter(...)
};

Binding an object from checkboxes

I need to bind an object from checkboxes, and in this example, a checkbox is its own component:
<input type="checkbox" :value="option.id" v-model="computedChecked">
Here's my data and computed:
data() {
return {
id: 1,
title: 'test title',
checked: {
'users': {
},
},
}
},
computed: {
computedChecked: {
get () {
return this.checked['users'][what here ??];
},
set (value) {
this.checked['users'][value] = {
'id': this.id,
'title': this.title,
}
}
},
....
The above example is a little rough, but it should show you the idea of what I am trying to achieve:
Check checkbox, assign an object to its binding.
Uncheck and binding is gone.
I can't seem to get the binding to worth though.
I assume you want computedChecked to act like an Array, because if it is a Boolean set, it will receive true / false on check / uncheck of the checkbox, and it should be easy to handle the change.
When v-model of a checkbox input is an array, Vue.js expects the array values to stay in sync with the checked status, and on check / uncheck it will assign a fresh array copy of the current checked values, iff:
The current model array contains the target value, and it's unchecked in the event
The current model array does not contain the target value, and it's checked in the event
So in order for your example to work, you need to set up your setter so that every time the check status changes, we can get the latest state from the getter.
Here's a reference implementation:
export default {
name: 'CheckBoxExample',
data () {
return {
id: 1,
title: 'test title',
checked: {
users: {}
}
}
},
computed: {
computedChecked: {
get () {
return Object.getOwnPropertyNames(this.checked.users).filter(p => !/^__/.test(p))
},
set (value) {
let current = Object.getOwnPropertyNames(this.checked.users).filter(p => !/^__/.test(p))
// calculate the difference
let toAdd = []
let toRemove = []
for (let name of value) {
if (current.indexOf(name) < 0) {
toAdd.push(name)
}
}
for (let name of current) {
if (value.indexOf(name) < 0) {
toRemove.push(name)
}
}
for (let name of toRemove) {
var obj = Object.assign({}, this.checked.users)
delete obj[name]
// we need to update users otherwise the getter won't react on the change
this.checked.users = obj
}
for (let name of toAdd) {
// update the users so that getter will react on the change
this.checked.users = Object.assign({}, this.checked.users, {
[name]: {
'id': this.id,
'title': this.title
}
})
}
console.log('current', current, 'value', value, 'add', toAdd, 'remove', toRemove, 'model', this.checked.users)
}
}
}
}