I am new to vuex and working on the best way to store the data inside vuex.
I have an array of objects:
teamData:[{
name: 'team1',
acronym: 't1',
color1: '#hexcode1',
color2: '#hexcode2',
},
{
name: 'team2',
acronym: 't2',
color1: '#hexcode1',
color2: '#hexcode2',
},
]
I have set a getter to
team1Name: (state) => state.teamData[0].name,
team1acronym: (state) => state.teamData[0].acronym,
is there a better way to map over this as the number of teams could change.
Looking to do a loop that will map over the length of the array and set the value that way
I think you can just pass the team number as parameter like this :
teamName: (state) => (teamNumber) => state.teamData[teamNumber].name,
teamAcronym: (state) => (teamNumber) => state.teamData[teamNumber].acronym,
Of course, this might need some check to see if the team exists like :
teamName: (state) => (teamNumber) => state.teamData[teamNumber] ? state.teamData[teamNumber].name : ""
Looking to do a loop that will map over the length of the array and set the value that way
I don't know if this is what you want but you can return all names from your store using the js map function
Example
teamNames: (state) => state.teamData.map(team => team.name)
Related
I have a cart, and it's an array of products, I am trying to access every name in the cart.
I have forEach function in getters, but it returns just one name. I have tried.map() but it returns another array and I need multiple string values. Can you please help?
let cart = window.localStorage.getItem('cart')
const store = createStore({
state: {
cart: cart ? JSON.parse(cart) : [],
},
getters: {
setTitle: state =>{
let oneItem=''
state.cart.forEach((item)=>{
oneItem=item.ropeTitle
})
return oneItem
},
}
}
It's because you're returning just oneItem (let me guess, it's also the last item in the state.cart array as well?)
What you can try instead is using .join() to join the item together.
Let's say you want to join items by , , you can try
setTitle: state => state.cart.map(item => item.ropeTitle).join(', ')
I wrote this code to return a list of skills. If the user already has a specific skill, the list-item should be updated to active = false.
This is my initial code:
setup () {
const user = ref ({
id: null,
skills: []
});
const available_skills = ref ([
{value: 'css', label: 'CSS', active: true},
{value: 'html', label: 'HTML', active: true},
{value: 'php', label: 'PHP', active: true},
{value: 'python', label: 'Python', active: true},
{value: 'sql', label: 'SQL', active: true},
]);
const computed_skills = computed (() => {
let result = available_skills.value.map ((skill) => {
if (user.value.skills.map ((sk) => {
return sk.name;
}).includes (skill.label)) {
skill.active = false;
}
return skill;
});
return result;
})
return {
user, computed_skills
}
},
This works fine on the initial rendering. But if I remove a skill from the user doing
user.skills.splice(index, 1) the computed_skills are not being updated.
Why is that the case?
In JavaScript user or an object is a refence to the object which is the pointer itself will not change upon changing the underling properties hence the computed is not triggered
kid of like computed property for an array and if that array get pushed with new values, the pointer of the array does not change but the underling reference only changes.
Work around:
try and reassign user by shadowing the variable
The computed prop is actually being recomputed when you update user.skills, but the mapping of available_skills produces the same result, so there's no apparent change.
Assuming user.skills contains the full skill set from available_skills, the first computation sets all skill.active to false. When the user clicks the skill to remove it, the re-computation doesn't set skill.active again (there's no else clause).
let result = available_skills.value.map((skill) => {
if (
user.value.skills
.map((sk) => {
return sk.name;
})
.includes(skill.label)
) {
skill.active = false;
}
// ❌ no else to set `skill.active`
return skill;
});
However, your computed prop has a side effect of mutating the original data (i.e., in skill.active = false), which should be avoided. The mapping above should clone the original skill item, and insert a new active property:
const skills = user.value.skills.map(sk => sk.name);
let result = available_skills.value.map((skill) => {
return {
...skill,
active: skills.includes(skill.label)
}
});
demo
slice just returns a copy of the changed array, it doesn't change the original instance..hence computed property is not reactive
Try using below code
user.skills = user.skills.splice(index, 1);
I have the following case
export const AssetList = types
.model({
assets: types.array(Asset),
})
.views((self) => ({
get current() {
console.log('current updated')
return self.assets.find((el) => el.liked === null)
},
}))
Then the Asset model looks like
export const Asset = types
.model({
liked: types.maybeNull(types.boolean),
})
.actions((self) => ({
like() {
console.log('like')
self.liked = true
},
dislike() {
console.log('dislike')
self.liked = false
},
}))
The problem comes when like() is fired, it updates the liked property of the Asset but then the AssetList computed property current does not update. Not sure why this is happening or if I need to add something extra in order to make it work.
I have around 300 records like this. Now it displays all items in the table. I want only Name,
proteins and kcal to be displayed in my table. How do I do this? I am fetching the list from an API.
[
{
"id":"711113fb-c3d1-46db-9f08-737a66ba643d",
"name":"Banana",
"fats":"0.2",
"carbohydrates":"11.8",
"proteins":"0.8",
"kcal":"46",
"tags":[
],
"tag_ids":[
],
"diet_phases":[
],
"diet_phase_ids":[
],
"product_group_id":"1cad5993-78f8-43b0-a0c5-f6f88fdf53b8",
"product_group_name":"Fruits"
},
productList: (state) => state.products.list,
This.items is an array which holds the items in my table.
mounted: this.fetchProducts().then(() => { this.items = this.productList; }); },
...mapActions ({
fetchProducts: "products/fetch",})
actions: {
fetch({ commit }) {
return api.products.list({}).then(({ data }) => {
commit(SET_LIST, data.results);
});
},
Still missing the template part of your component, and I don't know the bootstrap-vue table. So I assume your this.items just renders out each key of your item object.
So you want to controll what is rendered in the JS code and not the template, you can use the map function. So instead of directly assigning it to this.items, you can do something like this:
this.items = this.productList.map((item) => {
return {
name: item.name,
proteins: item.proteins,
kcal: item.kcal,
};
});
so I am trying to display data on my doughnut chart and I am having issues accessing my data from a nested array. When I use the following it just gives me the selected index of the nested array.
So I am wondering is there something else I need to do the computed data or if there is something I am doing wrong.
here is the computed property
countEngagementsByStatus () {
const selectedWorkflow = this.allWorkflows.filter(workflow => workflow.id === this.workflowKey)
const res = selectedWorkflow.map(({statuses, id}) => ({
workflow_id: id,
statuses: statuses.reduce((acc, cur) => {
const count = this.allEngagements.filter(({workflow_id, status}) => workflow_id === id && status === cur.status).length;
acc.push(count);
return acc;
}, [])
}))
return res
},
And on my doughnut chart I am accessing the data. *note removed styling data to clean up the question
datasetsfull() {
return {
labels: this.mapStatuses[0].statuses,
datasets: [
{
label: 'Data One',
data: [
//this is the line I have issues with
this.countEngagementsByStatus[0].statuses[0]
]
}
]
}
},
here is an image of what I am getting
Now If I do this
data: [
this.countEngagementsByStatus[0]
]
I get this as a result however it cannot access the array of numbers shown
So my question is, am I doing something wrong with computed property or am I accessing the data incorrectly or both? Lol
Here is a Js Fiddle To give an idea
So my issue was I was wrapping the data in an array
data: [
this.countEngagementsByStatus[0].statuses
]
I changed it to this
data: this.countEngagementsByStatus[0].statuses