Always first filtered selected on Quasar Select - vue.js

I am using Quasar Framework and using the Q-Select with filter.
I would like to the first filtered option always be already marked, because then if I hit enter, the first will selected.

After some research I found out how to achieve this in a generic way.
The second parameter on the function update received at filterFn is the instance of QSelect itself.
Hence, we can use
ref.setOptionIndex(-1);
ref.moveOptionSelection(1, true);
To keep the focus on the first filtered element, regardless of multiselect or not.
The final code is something like
filterFn(val, update) {
update(
() => {
const needle = val.toLocaleLowerCase();
this.selectOptions = this.qSelectOptions.filter(v => v.toLocaleLowerCase().indexOf(needle) > -1);
},
ref => {
ref.setOptionIndex(-1);
ref.moveOptionSelection(1, true);
});
}

There is one option to achieve this is set model value in the filter method if filtered options length is >0.
filterFn (val, update, abort) {
update(() => {
const needle = val.toLowerCase()
this.options = stringOptions.filter(v => v.toLowerCase().indexOf(needle) > -1)
if(this.options.length>0 && this.model!=''){
this.model = this.options[0];
}
})
}
Codepen - https://codepen.io/Pratik__007/pen/QWjYoNo

Related

read from database and change state within the same asynchronous call with the database result [duplicate]

I am recently learning the map and filter method in react native and I have a question. After finding a particular row of my array (with filter), how do I set only a particular field of that specific row?
I have
this.state = {
post: [{ id: "0", author: "Duffy Duck", delay: "1", picture: "" }]
}
putpicture(id) {
const picture_new = "/gggg(yyb45789986..."
const data = this.state.post
.filter((item) => item.author == id)
// my error is here. How can i put picture_new const, inside post.picture?
.map((pictures) => this.setState({ post.picture: picture_new }))
}
Now i want setState inside map and filter for every post.
i want this output:
id:"0", author:"Duffy Duck",delay:"1", picture:"/gggg(yyb45789986..."
How can i do?
It seems to me that you're only looking to change one particular entry of your array.
It also seems like you meant to search by id and not author.
If that's the case, you'll want to use findIndex to find the correct index.
Make a shallow copy of the array so as not to modify the original.
Then assign a modified copy of that object to that index, again so as not to modify the original.
Then assign the new array to the state.
Since the updated state relies on the previous state, you should house all of this within a setState callback function. This is because state updates may be asynchronous, as outlined here: https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous. In other words, this ensures you get the most up to date version of your state at the time of applying the change.
putpicture(id) {
const picture_new = '/gggg(yyb45789986...';
this.setState(({ post }) => {
// find index of item to edit
const index = post.findIndex((item) => item.id === id);
if (index === -1) return;
// create shallow copy of array
const newPost = [...post];
// replace old object with new object
newPost[index] = { ...post[index], picture: picture_new };
return { post: newPost };
});
}
Stackblitz: https://stackblitz.com/edit/react-ts-ht8hx9?file=App.tsx
If I've misunderstood your intentions, please reword your question to be more clear. You use the term "row of my array", but this a 1-dimensional array, there are no rows. In the question you also mention modifying "every post", but in a comment you mention modifying only "a post".
This doesn't 100% make sense to me - are you sure you want to set all pictures on posts by an author at once? Is the post array meant to hold multiple posts? It looks like that's the goal based on the code, so I'll answer that as is.
EDIT: changed to reflect one post at a time.
You're close to a solution - the things you're missing are
You can use .find instead of .filter since you only want one post
Since you can use .find, which returns a single item, you don't need to .map.
putpicture(id) {
const picture_new = "/gggg(yyb45789986...";
const modifiedPost = this.state.post.find((item) => item.id === id);
modifiedPost.picture = picture_new;
// now that you have the modified post, put it into state
// first, get all the other (unmodified) posts
const otherPosts = this.state.post.filter((item) => item.id !== id);
// add the new post to the array and set state
this.setState({ post: [...otherPosts, modifiedPost] });
}
As an aside, if you're going to be doing this a lot, I would recommend making your state an object with IDs as the keys, instead of an array. .find and .filter loop over each array member and can do a lot of unnecessary work. If you set up your state like this:
this.state = {
post: {
0: { id: "0", author: "Duffy Duck", delay: "1", picture: "" },
}
};
then you can modify it much more easily:
putpicture(id) {
const picture_new = "/gggg(yyb45789986...";
const newPosts = {
...this.state.post,
[id]: {
...this.state.post[id],
picture: new_picture,
}
};
this.setState({ post: newPosts });
}
This is much faster when dealing with large arrays.
In case you can have more than one post in array and anything apart of post in you state:
putpicture(id) {
const picture_new = "/gggg(yyb45789986...";
// create new array by reducing source array
const newPost = this.state.post.reduce((res, it) => {
// update only item(s) matching the condition
res.push(it.author === id ? {...it, picture: picture_new} : {...it});
return res;
}, []);
// use destructuring and previous state to update the state
this.setState(prev => {...prev, post: newPost});
}

How can I access to each element inside of a grid element with Cypress?

I have a Grid component which includes 24 divs and inside of each div I need to take the value.
This value actually arrives in <p>, so which is the best way to do this?
Below is the app image. I would appreciate an example.
You could probably do something like storing the data in an object or array outside of the Cypress chain. Without a code example, here's my best guess.
cy.get('grid').within(() => { // cy.within() searches only within yielded element
const data = {}; // create data object
cy.get('div').each(($div, index) => { // cy.each() allows us to iterate through yielded elements
data[index] = $div.text() // or possibly some other JQuery command to get the value
// additionally, could go without the index at all and make `data` an array.
}).then(() => {
// whatever needs to be done with `data`, wrapped in `then` to make sure data is populated correctly.
});
});
You can add use each for this to loop through the elements and then do further operations:
cy.get('.chakra-stack')
.find('p')
.each(($ele) => {
cy.log($ele.text().trim()) //Logs all the texts one by one
})
Just add the p selector to your cy.get() command
cy.get('div.chakra-stack p') // access <p> within <div>
.each($el => {
cy.wrap($el).invoke('text')
.then(text => {
...
})
})
To get the value before the text
cy.get('div.chakra-stack p') // access <p> within <div>
.each($el => {
cy.wrap($el)
.prev() // element with value
.invoke('text')
.then(value => {
...
})
})
Accessing values by text label like this
const values = {}
cy.get('div.chakra-stack p')
.each($el => {
const frase = $el.text()
cy.wrap($el).prev().invoke('text')
.then(value => values[frase] = +value)
})
.then(() => {
// values = {'shield': 1, 'session': 2, ...}
})

FlatList single select cell

I followed the example from official docs, here is how to implement multiselection feature:
state = { selected: (new Map(): Map<string, boolean>) };
onPressItem = (id) => {
this.setState((state) => {
const selected = new Map(state.selected);
selected.set(id, !selected.get(id));
return { selected };
});
};
I'm struggling with making it single select though. It's easy to return new Map with false values anytime cell is tapped, but that means the cell cannot be deselected by another tap on it, which is the desired feature in my case.
onPressItem = (id) => {
this.setState((state) => {
const selected = new Map();
selected.set(id, !selected.get(id));
return { selected };
});
};
How would you implement it? Should I use lodash to iterate over the Map to find the one that already is true and change its value (now sure how to iterate over Map though), or maybe there is some better approach I am missing right now?
EDIT
Iterating over elements of the selected Map seems to be a really ugly idea, but it is simple and it actually works. Is there any better way to do it that I am missing out on?
onPressItem = (id: string) => {
this.setState((state) => {
const selected = new Map(state.selected);
selected.set(id, !selected.get(id));
for (const key of selected.keys()) {
if (key !== id) {
selected.set(key, false);
}
}
return { selected };
});
};
Thanks in advance
You can just set only one value instead of a map like this
onPressItem = (id) => {
this.setState((state) => {
const selected = selected === id ? null : id;
return { selected };
});
};
I had the same issue, my solution was:
_onPressItem = (id: string) => {
// updater functions are preferred for transactional updates
this.setState((state) => {
// copy the map rather than modifying state.
const selected = new Map(state.selected);
// save selected value
let isSelected = selected.get(id);
// reset all to false
selected.forEach((value, key) => {
selected.set(key, false);
});
// then only activate the selected
selected.set(id, !isSelected);
return { selected };
});
};

Apply filter to API response - vue.js

I have this method to get data from an API, which sends me information of many furniture pieces:
loadPieces() {
this.isLoading = true;
axios.get(this.galleryRoute)
.then(r => {
this.gallery = r.data;
this.isLoading = false;
})
.catch(error => {
this.$nextTick(() => this.loadPieces());
});
console.log(this.galleryRoute);
},
This is a part of the response I get, which represents only one piece:
[[{"id":266,"name":" Tray 7x45x32, white stained ash","thumbnail":{"width":840,"height":840,"urls":{"raw":"http:\/\/localhost:8888\/storage\/9c\/9d\/9c9dadc6-15a2-11e8-a80a-5eaddf2d1b4a.jpeg","small":"http:\/\/localhost:8888\/storage\/9c\/9d\/9c9dadc6-15a2-11e8-a80a-5eaddf2d1b4a#140.jpeg","medium":"http:\/\/localhost:8888\/storage\/9c\/9d\/9c9dadc6-15a2-11e8-a80a-5eaddf2d1b4a#420.jpeg"}}},
Now I want to create a filter so that I can get a specific piece from the JSON object, using it's id. I've tried searching but so far I have no idea how to do this.
Thanks in advance!
Add a computed property which applies the filter to this.gallery:
computed: {
filteredGallery() {
if (!this.gallery) return []; // handle gallery being unset in whatever way
return this.gallery.filter(picture =>
// some reason to show picture
);
}
}
I'm assuming gallery is an array, but you could apply a similar technique to it if it was an object, using e.g. Object.keys(this.gallery).
Then in your template, use filteredGallery instead of gallery.

Lists and Components not updating after data change - (VueJS + VueX)

A question about best practice (or even a go-to practice)
I have a list (ex. To-do list). My actual approach is:
On my parent component, I populate my 'store.todos' array. Using a
getter, I get all the To-do's and iterate on a list using a v-for
loop.
Every item is a Component, and I send the to-do item as a prop.
Inside this component, I have logic to update the "done" flag. And this element display a checkbox based on the "state" of the flag. When it does that, it do an action to the db and updates the store state.
Should I instead:
Have each list-item to have a getter, and only send the ID down the child-component?
Everything works fine, but if I add a new item to the to-do list, this item is not updated when I mark it as completed. I wonder if this issue is because I use a prop and not a getter inside the child component
Code:
store:
const state = {
tasks: []
}
const mutations = {
CLEAR_TASKS (state) {
state.tasks = [];
},
SET_TASKS (state, tasks) {
state.tasks = tasks;
},
ADD_TASK (state, payload) {
// if the payload has an index, it replaces that object, if not, pushes a new task to the array
if(payload.index){
state.currentSpaceTasks[payload.index] = payload.task;
// (1) Without this two lines, the item doesn't update
state.tasks.push('');
state.tasks.pop();
}
else{
state.tasks.push(payload.task);
}
},
SET_TASK_COMPLETION (state, task){
let index = state.tasks.findIndex(obj => obj.id == task.id);
state.tasks[index].completed_at = task.completed_at;
}
}
const getters = {
(...)
getTasks: (state) => (parentId) => {
if (parentId) {
return state.tasks.filter(task => task.parent_id == parentId );
} else {
return state.tasks.filter(task => !task.parent_id );
}
}
(...)
}
const actions = {
(...)
/*
* Add a new Task
* 1st commit add a Temp Task, second updates the first one with real information (Optimistic UI - or a wannabe version of it)
*/
addTask({ commit, state }, task ) {
commit('ADD_TASK',{
task
});
let iNewTask = state.currentSpaceTasks.length - 1;
axios.post('/spaces/'+state.route.params.spaceId+'/tasks',task).then(
response => {
let newTask = response.data;
commit('ADD_TASK',{
task: newTask,
index: iNewTask
});
},
error => {
alert(error.response.data);
});
},
markTaskCompleted({ commit, dispatch, state }, task ){
console.log(task.completed_at);
commit('SET_TASK_COMPLETION', task);
dispatch('updateTask', { id: task.id, field: 'completed', value: task.completed_at } ).then(
response => {
commit('SET_TASK_COMPLETION', response.data);
},
error => {
task.completed_at = !task.completed_at;
commit('SET_TASK_COMPLETION', task);
});
},
updateTask({ commit, state }, data ) {
return new Promise((resolve, reject) => {
axios.patch('/spaces/'+state.route.params.spaceId+'/tasks/'+ data.id, data).then(
response => {
resolve(response.data);
},
error => {
reject(error);
});
})
}
}
And basically this is my Parent and Child Components:
Task List component (it loads the tasks from the Getters)
(...)
<task :task = 'item' v-for = "(item, index) in tasks(parentId)" :key = 'item.id"></task>
(...)
The task component display a "checkbox"(using Fontawesome). And changes between checked/unchecked depending on the completed_at being set/true.
This procedure works fine:
Access Task list
Mark one existing item as done - checkbox is checked
This procedure fails
Add a new task (It fires the add task, which firstly adds a 'temporary' item, and after the return of the ajax, updates it with real information (id, etc..). While it doesn't have the id, the task displays a loading instead of the checkbox, and after it updates it shows the checkbox - this works!
Check the newly added task - it does send the request, it updates the item and DB. But checkbox is not updated :(
After digging between Vue.js docs I could fix it.
Vue.js and Vuex does not extend reactivity to properties that were not on the original object.
To add new items in an array for example, you have to do this:
// Vue.set
Vue.set(example1.items, indexOfItem, newValue)
More info here:
https://v2.vuejs.org/v2/guide/reactivity.html
and here: https://v2.vuejs.org/v2/guide/list.html#Caveats
At first it only solved part of the issue. I do not need the "hack" used after pushing an item into the array (push and pop an empty object to force the list to reload)
But having this in mind now, I checked the object returned by the server, and although on the getTasks, the list has all the fields, including the completed_at, after saving a new item, it was only returning the fields that were set (completed_at is null when created). That means that Vue.js was not tracking this property.
I added the property to be returned by the server side (Laravel, btw), and now everything works fine!
If anybody has a point about my code other than this, feel free to add :)
Thanks guys