How can I add new values to an array object of state using Vuex? - vue.js

My code like this :
<template>
...
...
</template>
<script>
export default {
...
methods: {
...mapActions([
'getDataDoctor',
'getDataSchedule'
]),
async visibilityChanged(isVisible, entry, item) {
let param = {
hospitalId: item.hospital_id,
doctorId: item.doctor_id
}
await this.getDataSchedule(param)
let data = this.dataDoctor
for (let key in data) {
this.$set(data[key].find(e => e.doctor_id === item.doctor_id && e.hospital_id === item.hospital_id), 'schedule', this.dataSchedule.schedule)
}
}
},
computed: {
...mapState({
dataDoctor: state => state.dataStore.dataDoctor,
dataSchedule: state => state.dataStore.dataSchedule
}),
},
}
</script>
If I console.log(this.dataDoctor), the result like this :
Or you can see the this.dataDoctor this : https://pastebin.com/yGjsTBjX
this.dataDoctor is state from vuex store. I want to add new value there. The name is schedule
I do like that. But there exist error like this :
Cannot set reactive property on undefined, null, or primitive value: undefined
Uncaught (in promise) TypeError: Cannot use 'in' operator to search for 'schedule' in undefined
How can I solve this problem?

This bit looks wrong:
for (let key in data) {
this.$set(data[key].find(e => e.doctor_id === item.doctor_id && e.hospital_id === item.hospital_id), 'schedule', this.dataSchedule.schedule)
}
From the sample data you posted this will only find something for (at most) one value of key. For the other values of key the find will return undefined and the $set will fail.
Try this:
for (const key in data) {
const entry = data[key].find(e => e.doctor_id === item.doctor_id && e.hospital_id === item.hospital_id)
console.log(`key is ${key}:`, entry)
if (entry) {
this.$set(entry, 'schedule', this.dataSchedule.schedule)
}
}
Of course it is also possible that none of the entries will match. The console logging I've included should help you to identify that scenario too.
I should add that it is usually regarded as best practice to mutate store state within a store mutation rather than directly inside a component.

Related

Vuex passing different arrays

Making a filter:
Mutations
export default {
state: {
filteredBrands: []
},
mutations: {
showFilteredList(state, payload) {
state.filteredBrands.push(payload);
}
}
};
Methods
loadProducts(item) {
axios.get('/api', {
params: {
per_page: 20,
filter_machinery_brands: [ item ]
}
})
.then((response) => {
this.$store.commit(
'showFilteredList',
response.data
);
});
},
item this is an input with a checkbox, when clicked, a request is made to the server for this category
For some reason, the push does not work, why?
And I would like there to be a check, if the array is the same, then delete, otherwise add. Is it possible?
If you can se an array comes in as payload. Then you are trying to push an array into an array. Which cant be done in either js or ts.
You can try set the value:
state.filteredBrands = payload;
otherwise you would have to do something like this:
state.filteredBrands.push(payload[0]);
If you wanna control for existing items in array, and assuming your are not always setting value, but pushing new values into your array. You can do something like this:
if (state.filteredBrands.indexOf(payload[0]) === -1) {
// Not in array
state.filteredBrands.push(payload[0])
} else {
// is allready in array
state.filteredBrands.forEach((item, index) => {
if (item === payload[0]) {
state.filteredBrands.splice(index, 1)
}
})
}
EDIT:
My assumption was right.
Your payload is an array
Your state is an array
-------> You are trying to push payload(array) into state(array) - which cant be done i js - This solution would after my suggestion be more clean:
payload.forEach((value, index) => { // Looping payload
if (state.filteredBrands.indexOf(value) === -1) {
state.filteredBrands.push(value) // push if value not allready in array
} else {
state.filteredBrands.splice(index, 1) // if value is in array -> remove
}
})
Yes, you can push an array into an array.
I guess the problem here is your vuex config.
Vuex state is a function, so it needs to be:
state () {
return {
filteredBrands: []
}
}
And if you are using Nuxt:
export const state = () => ({
filteredBrands: []
})

Why i am getting a warning about of string type if i am passing a string?

i want to pass a String to my child component like this, but previously i want to print it
this is my parent component
{{left.leftA}} // here show me 8
<CustomCard
:left="left.leftA"
export default {
name: 'Parent',
data() {},
setup() {
onMounted(async () => {
const answer = await getData(name)
left.value = answer.response //{leftA:'A', leftB:'B'...}
})
and in my child component i have this declaration
export default {
name: 'CustomCard',
props: {
left: {
type: String,
required: true,
},
i am getting this warning:
[Vue warn]: Invalid prop: type check failed for prop "left". Expected String with
value "undefined", got Undefined
Does it have something to do with how I am loading the data? is it ok to use onMounted?
This is happening because the initial value for value is null. So, on initial render it throws the warning, but upon another render it has the correct prop type (a string) and renders correctly.
You have 3 options. Allow '' as an option on the prop or don’t render the component until you have the correct data or make use of computed Property.
Option-1
{{left.leftA}} // here show me 8
<CustomCard
:left="left.leftA ? left.leftA : ''"
Option-2
{{left.leftA}} // here show me 8
<CustomCard v-if="loaded"
:left="left.leftA"
and in onMounted(}
onMounted(async () => {
const answer = await getData(name)
left.value = answer.response //{leftA:'A', leftB:'B'...}
// Set the loaded flag as true here. Also make sure its set as false inside the setup()
})
Option-3
{{left.leftA}} // here show me 8
<CustomCard
:left="sendVal"
In computed....
computed: {
sendVal() {
if(left && left.left1) return left.left1;
return '';
}
}

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 []
}

VUEJS Can’t use api response data in the template

I need to populate a table using an array of objects got by an api call (axios).
This part is working fine.
In the store module (activity.js) I declared the array:
currentUserActivities: [],
In the mutations:
SET_CURRENT_USER_ACTIVITIES: (state, currentUserActivities) => {
state.currentUserActivities = currentUserActivities
},
In the actions:
setCurrentUserActivities({ commit }, userId) {
return new Promise((resolve, reject) => {
getUserActivities(userId).then(response => {
const currentUserActivities = response.results
commit('SET_CURRENT_USER_ACTIVITIES', currentUserActivities)
console.log('response current user activities: ', response.results)
resolve()
}).catch(error => {
console.log('Error setting single user activities: ', error)
reject(error)
})
})
},
Then I saved it in the getters module as so:
currentUserActivities: state => state.activity.currentUserActivities,
In the vue page, the relevant part of the script:
data() {
return {
currentUser: {},
userId: {
type: Number,
default: function() {
return {}
}
},
currentUserActivities: [],
}
},
mounted() {
const userId = this.$route.params.userId
this.$store.dispatch('user/setCurrentProfile', userId).then(() => {
const currentUser = this.$store.getters.currentProfile.user
this.currentUser = currentUser
console.log('user mounted user', currentUser)
this.$store.dispatch('activity/setCurrentUserActivities', userId).then(() => {
const currentUserActivities = this.$store.getters.currentUserActivities
console.log('activities on mounted', currentUserActivities)
})
})
},
In the template part, as I said, I will have a table data. Let's forget about it for now, I am just trying to get the array displayed raw, as so:
<div>
<p v-if="currentUserActivities.length = 0">
This user has no activities yet.
</p>
<p>CURRENT ACTIVITIES: {{ currentUserActivities }}</p>
<p>CURRENT USER: {{ currentUser }}</p>
</div>
The current user is displaying fine, in the browser I can see:
CURRENT USER: { "id": 1, "last_login": "20/09/2019 09:42:15", "is_superuser": false, "username": "admin", "first_name": "System", "last_name": "Dev", "email": "systems#dev.it", "is_staff": true, "is_active": false, "date_joined": "30/08/2019 09:03:40" }
The current user activities array, instead:
CURRENT ACTIVITIES: []
In the console I have both, leaving the user which is fine, the current user activities array is:
activities on mounted:
0: {...}
1: {…}
2:
activity: (...)
arrival_point: "SRID=4326;POINT (0 0)"
burns_calories: false
co2: "0.00"
co2_production: (...)
cost: (...)
created: (...)
default_cost: (...)
end: (...)
ecc. It's there, we can see it.
Inside the mounted, if we compare the code written for the user and the activities, the only difference is that I didn't set
this.currentUserActivities = currentUserActivities
If I do that, I loose the data in the console too (on the screen it remains empty array).
In the console I would have:
activities on mounted: (5) [{…}, {…}, {…}, {…}, {…}, __ob__: Observer]
1. length: 0
2. __ob__: Observer {value: Array(0), dep: Dep, vmCount: 0}
3. __proto__: Array
Also, even if I set
v-if="currentUserActivities.length = 0"
to display a p tag in case the array is really empty, it doesn't get displayed. This too is not right. I don't know if they can be related.
I tried many many subtle different versions of code, but none of them worked.
I know I am missing something (code is never wrong....) ....
Can someone enlighten me, please?
Thanks a lot.
x
First up, this:
this.$store.dispatch('activity/setCurrentUserActivities', userId).then(() => {
const currentUserActivities = this.$store.getters.currentUserActivities
console.log('activities on mounted', currentUserActivities)
})
As you've noted in the question, you aren't assigning currentUserActivities to anything. It should be this:
this.$store.dispatch('activity/setCurrentUserActivities', userId).then(() => {
const currentUserActivities = this.$store.getters.currentUserActivities
this.currentUserActivities = currentUserActivities
console.log('activities on mounted', currentUserActivities)
})
I know you mentioned that this didn't work in the question but it is required to get it working. It isn't sufficient, but it is necessary.
The reason the array appears empty is because of this:
v-if="currentUserActivities.length = 0"
Note that you are setting the length to 0, not comparing it to 0. It should be:
v-if="currentUserActivities.length === 0"
You've got some other problems too, though they're not directly related to the empty array.
Generally you shouldn't have data values for state in the store (unless you're taking copies for editing purposes, which you don't seem to be). Instead they should be exposed as computed properties, e.g.:
computed: {
currentUser () {
return this.$store.getters.currentProfile.user
}
}
Vuex includes a helper called mapGetters that can be used to shorten this a little, see https://vuex.vuejs.org/api/#component-binding-helpers, though some people prefer the explicitness of the longer form.
This is also a little strange:
return new Promise((resolve, reject) => {
getUserActivities(userId).then(response => {
Generally creating a new promise is regarded as a code smell as it is very rarely necessary. In this case you should probably just be returning the promise returned by getUserActivities instead. e.g.:
return getUserActivities(userId).then(response => {
Obviously you'd need to make other adjustments to accommodate the resolve and reject functions no longer being available. Instead of resolve you'd just return the relevant value (though there doesn't seem to be one in your case) and for reject you'd just throw the error instead.
I also notice that userId in your data is being assigned a type and default. Note that this is prop syntax and isn't valid for data properties. It isn't an error but the userId will just be equal to that whole object, it won't treat it as a configuration object.

Why "Error in render: TypeError: Cannot read property 'filter' of undefined" returned even data already available?

I already initialize the data.
data () {
return {
current_product: {},
current_ID: '',
}
}
Then, I fetch data from a REST API on lifecycle created hook.
created () {
var skuID = this.$store.state.selected_productSKU.productSKU_ID
axios.get(`http://localhost:8081/api/products/${skuID}`)
.then(response => {
this.current_ID = response.data.product_ID
this.current_product = response.data
})
.catch(e => {
alert(e)
})
}
And finally, I use computed property to get some value
// THIS JUST RETURN ['XL', 'M']
focusedProduct_SKUS_NoDupSizes () {
var newArr = this.current_product.product_SKU.filter((sku, index, self) =>
index === self.findIndex(t => (
t.productSKU_size === sku.productSKU_size
))
)
var x = newArr.map(a => a.productSKU_size)
return x
}
The vue instance show expected result
But if i call {{ focusedProduct_SKUS_NoDupSizes }} in template.
It doesn't rendered.
The browser return error Error in render: "TypeError: Cannot read property 'filter' of undefined"
What is happening? My first guess is the computed property using the initial structure of current_product which is {} empty object. But isn't that how to initialize an object?
Because of:
computed:
// ...
focusedProduct_SKUS_NoDupSizes () {
var newArr = this.current_product.product_SKU.filter((sku, index, self) =>
^^^^^^^^^^^
You should initialize product_SKU with an empty array:
data () {
return {
current_product: {product_SKU: []}, // changed here
current_ID: '',
}
}
This is needed because the computed property will be executed right away, even before your Ajax gets a chance to return.
Declare it as empty so the computed doesn't throw an error. When the Ajax fulfills, it will recompute automatically.
Even though the Ajax is started at the created(), it won't return before the computed is executed for the first time. More details about this here.