Vue - Array dosen't update - vue.js

On click, I want to push to array. It works if I manually refresh the Vue extension in the console of Google Chrome but otherwise not
completeStep(index, key) {
let currentSet = index + key
if (this.exercise_completed[index].indexOf(currentSet) === -1) {
this.exercise_completed[index].push(currentSet)
} else {
this.exercise_completed[index].splice(this.exercise_completed[index].indexOf(currentSet), 1)
}
}

maybe try to use this.$forceUpdate(); when you make the change.
https://v2.vuejs.org/v2/api/#vm-forceUpdate
Hope this helps

I would recommend making a key and changing the key on changes in the array. See here:
https://michaelnthiessen.com/force-re-render

Related

Push method in useState hook || REACT NATIVE

I have an array of items in a state variable like this.
const [items, setItems] = useState(["item1", "item2", "item3")])
How to replace one item in the array. Below is the method I have used to get it done.
{
let dummy = [...items]
dummy[1] = "items 1.1"
setItems(dummy)
}
But, I am thinking that this is not at all the right way to do this.
Is there any other simplified way to solve this? Thanks in Advance
Your solution is not wrong, but I would add an extra check to make sure that items array contains an element which you wish to change.
let dummy = [...items]
if(typeof dummy[1] == 'undefined') {
// does not exist
}
else {
// does exist
dummy[1] = "items 1.1"
}
setItems(dummy)
Or you can use slice
const idxToChange = 1
setItems([items.slice(0, idxToChange), "items 1.1", items.slice(idxToChange+1, items.length)])
A good explanation of slice
https://www.w3schools.com/jsref/jsref_slice_array.asp
Heres another way to do it. I don't know it's cleaner for you or not.
setItems(items=> items.map((item,idx)=> idx===1?"items 1.1":item));

how to reload value after clicking in vue

I'm trying to reload values when switching tab without reloading the page. I'm getting the value from a method.
mounted() {
this.getOriginalSpace();
},
methods: {
getOriginalSpace() {
retrieveQuotaSummary(this.value.organisation, this.value.dataCenter)
.then((result) => {
this.quotaSummary = result;
});
}
}
after that, I read the needed value out of quotaSummary like this (computed):
previouslyYarnCPU() {
return this.quotaSummary.currentAcceptedYarnRequest
? this.quotaSummary.currentAcceptedYarnRequest.cpu
: 0;
},
Then, when I switch tab, and call an other function in computed mode, I still have the same value which was loaded above. But when I refresh the page, then I get the correct (new value).
Can someone please help me, how I can get the latest values without refreshing the whole page?
It is difficult as I would need to see the rest of your code but in order to get values when they change you need to use a computed function. You can read more here

Why does data in list1 changed automatically when I change the data in the other list2 which is cloned from the list1? Using Vue.Draggable

I am using Vue.Draggable in my Vue project and trying to drag(clone) a button from sider into a draggable component.
I want to modify the data when I clone the button into the component. But I find that when I modify the data in the list which is binded with the component, the original list that sider used got changed automatically.
Is there some kind of synchronization mechanism in Vue.Draggable or something? I want to change the object data in the component only.
I tried to modify the object in the list2 manually by using a vue extension in Chrome browser. And it still happens. So I think maybe it's not bug in my code.
addEntity (conditionID, entity) {
if (!entity.forChoose) {
}
else {
let variable = 0;
for (let i = 0, len = this.whens.length; i < len; i++) {
if (this.whens[i].entity[0].id == entity.id) {
variable++;
}
}
this.whens[conditionID].entity[0].forChoose = false;
this.whens[conditionID].entity[0].variable = variable;
this.whens[conditionID].entity[0].name = entity.name + '-fake';
}
},
The code above is the event when I drag the data into the component, and changed some variable.
Although I did nothing to the original data in the Sider where I cloned the data from, it still got changed as well.
Is there a way to change the dragged data but do not affect the original data?
Please help me, thank you!
I think this is happening because of the immutability.
so can you try using spread operator to create new shallow copy of your list before you change it.
how to use spread operator (triple dot)
let newArrayOfWhens = [...this.whens]
then use the "newArrayOfWhens" array in your code
You can create a deep clone as well if you want, but try to avoid it if it is not necessary.
you can use a library call "lodash" to do it very easily
deepClone

Is it possible to remove all items from AsyncStorage

I'm testing my React-Native application and want to remove all items from AsyncStorage in order to test the app from the beginning. And I am a bit confused.
I read the official documentation and found multiRemove and clear functions, but I cannot understand how to clear all items of my application (clear as far as I understood clear the whole storage of all applications and I'm afraid to use it),
and multiRemove delete only keys that I give it in parameters, but I want to clear all keys.
I suppose I can do it through getAllKeys keys-values and remove it one-by-one, but maybe there is a more clear way to do it? :)
thanks
P.S: I tried to to like this:
clearAllData() {
AsyncStorage.multiRemove([]).then(() => alert('success'));
}
but it doesn't work...
I suppose I can do it through getAllKeys keys-values and remove it one-by-one, but maybe there is a more clear way to do it? :)
You should do that, that's the only way to remove all keys from your app.
Here is a simple way of doing it:
clearAllData() {
AsyncStorage.getAllKeys()
.then(keys => AsyncStorage.multiRemove(keys))
.then(() => alert('success'));
}
When your app runs, it is assigned a unique ID. Each stored key is prefixed by the ID. Therefore, all YOUR app's keys can be identified.
Using AsyncStorage.clear does not use unique identifiers and will delete keys for all clients, apps, and libraries. This might be OK in development but probably undesirable in production.
Per #Bruno Soares, multiRemove is preferred. However, note that 'await' can only be used within an async function. Combining Bruno's answer with #Prawesh Panthi, the following function will delete keys that are only associated with your app without having to explicitly identify the keys.
removeAppKeys = async () => {
let keys = []
try {
keys = await AsyncStorage.getAllKeys()
console.log(`Keys: ${keys}`) // Just to see what's going on
await AsyncStorage.multiRemove(keys)
} catch(e) {
console.log(e)
}
console.log('Done')
}
removeFew = async () => {
const keys = ['#MyApp_USER_1', '#MyApp_USER_2']
try {
await AsyncStorage.multiRemove(keys)
} catch(e) {
// remove error
}
console.log('Done')
}
Here a way of doing it, using async/await:
const keys = await AsyncStorage.getAllKeys()
await AsyncStorage.multiRemove(keys)

Radio button in polymer already selected

I'm loading a radio-button-group in polymer with a set of 4 radio buttons as answer options to a question. I have 4 questions. Now if I select an option in the first question and select next(go to the next question), the second question has its option already selected(same as the first question). Why is this happening?
<paper-radio-group>
<template is="dom-repeat" items=[[_calculateQuestionOptions(index)]]>
<paper-radio-button name="{{_calculateId(index)}}">
[[item.questionOption]]
</paper-radio-button><br>
</template>
</paper-radio-group>
CODE for next and prev operations
next() {
if (this.index < this.repos.length-1) {
this.index +=1;
}
}
prev() {
if (this.index>0) {
this.index -= 1;
}
}
To solve this issue. I wanted to add all the answers to an array and clear the selection as soon as the next button is click. Somthing like this.
next() {
var questionId = this.repos[this.index].questionId;
if (Polymer.dom(this.root).querySelector("paper-radio-group")) {
this.answers[questionId] = Polymer.dom(this.root).querySelector("paper-radio-group").selected;
Polymer.dom(this.root).querySelector("paper-radio-group").selected = null;
}
if (this.index < this.repos.length-1) {
this.index +=1;
}
questionId = this.repos[this.index].questionId;
if (this.answers[questionId] !== null) {
Polymer.dom(this.root).querySelector("paper-radio-group").selected = this.answers[questionId];
}
}
Is this the only way or is there a better way to do this.
Why is this happening?
It happens because dom-repeat reuse old elements when it update (for better performance, re-create DOM is slow). Its means only bound data in that scope will be updated.
Is this the only way or is there a better way to do this.
I think your way is already fine but you still can reduce some code by using advantage of Polymer like:
Static node map here
Complex observers here
My example see here
Thanks.