How to apply a settimeout in the VUEJS script? - javascript

I am developing my first application in vuejs and in the initial data upload in the script I need to modify the data I received from a call to the database.
Since I have modified the data it returns an error in the initial load of the page and after a few seconds it loads without problem.
I am trying to wrap this function in a settimeout but it returns an error in vuejs.
How can I apply this setTimeout?
here my script
<script>
export default {
data () {
return {
step: 1,
selected: 1
}
},
components: {
},
computed:{
selectedBasket() {
return !this.$store.getters.basket ? null : this.$store.getters.basket
},
items(){
return !this.$store.getters.items ? null : this.$store.getters.items
},
setTimeout(() => {
filteredEstimation(){
this.$store.getters.estimations.map(function(estimation) {
estimation.offers.map(function(offer) {
offer.name = offer.name.split(" ").reverse().slice(1).reverse().join(" ");
if (offer.name.includes("first")) {
offer.description = "first option";
}
if (offer.name.includes("second")) {
offer.description = "second option";
}
if (offer.name.includes("third")) {
offer.description = "third option";
}
});
});
return !this.$store.getters.estimations ? null : this.$store.getters.estimations.filter( item => item.id == this.selected )[0].offers
}, 700);
},
methods: {
getItemsName(item) {
if(item == 1){
return 'bag'
} else if(item == 2){
return 'paper'
} else {
return 'pen'
}
}
}
}
</script>

You're using that function inside the computed option, that's not allowed, you should define it in the mounted hook like :
<script>
export default {
data () {
return {
step: 1,
selected: 1
}
},
components: {
},
computed:{
selectedBasket() {
return !this.$store.getters.basket ? null : this.$store.getters.basket
},
items(){
return !this.$store.getters.items ? null : this.$store.getters.items
},
},
methods: {
getItemsName(item) {
if(item == 1){
return 'bag'
} else if(item == 2){
return 'paper'
} else {
return 'pen'
}
}
},
mounted(){
setTimeout(() => {
filteredEstimation(){
this.$store.getters.estimations.map(function(estimation) {
estimation.offers.map(function(offer) {
offer.name = offer.name.split(" ").reverse().slice(1).reverse().join(" ");
if (offer.name.includes("first")) {
offer.description = "first option";
}
if (offer.name.includes("second")) {
offer.description = "second option";
}
if (offer.name.includes("third")) {
offer.description = "third option";
}
});
});
return !this.$store.getters.estimations ? null : this.$store.getters.estimations.filter( item => item.id == this.selected )[0].offers
}, 700);
}
}
</script>

Related

Vue metaInfo undefined in watch

I am inserting vue-meta logic inside the current code and there seems to be a problem that metaInfo is not available yet when watch is triggered.
export default {
metaInfo () {
return {
title: this.title,
meta: [],
}
},
watch: {
article() {
if (this.article) {
this.generatedHtml = this.applySnippets();
}
},
},
computed: {
article() {
return this.$store.getters.CONTENT;
},
title() {
if (this.article !== null) {
return this.article.info.caption;
}
return '';
},
}
created() {
this.$store.commit('CLEAR_CONTENT');
this.$store.dispatch('FETCH_CONTENT', { slug: this.slug, component: this });
},
methods: {
applySnippets() {
if (!this.article.snippets || this.article.snippets.length === 0) {
return this.article.data.content;
}
this.article.snippets.forEach(snippet => {
if (snippet.type === 'meta')
this.metaInfo.meta.push(snippet.object);
});
},
It fails that this.metaInfo is undefined during this Vue lifecycle phase. What to do?
To access the metaInfo result in the Options API, use this.$metaInfo (note the $ prefix):
if (snippet.type === 'meta')
this.$metaInfo.meta.push(snippet.object);
👆
demo

How to make search case insensitive in Angular

I have a list of data names and I want to search through it. It should give result irrespective of the case.
this is what I have:
public groups = [{ name: '"Grx-1"', selected: false }, { name: '"Grx-man-2"', selected: false }, { name: '"Grx-up-3"', selected: false }];
queryGroups(groupName) {
this.groups = this.totalGroupsList.filter((group) => {
if (group.userId.includes(groupName) || group.dps.includes(groupName) || group.sourceType.includes(groupName)) {
return true;
} else {
let isRole = false;
group.role.forEach((role) => {
if (role.name.includes(groupName)) {
isRole = true;
return;
}
});
if (isRole === false) {
return false;
} else {
return true;
}
}
});
}
If I search for "Grx" I get all the results. I want that if I search for "grx" i should get all the results.
You can use toLowerCase()
role.name.toLowerCase().includes(groupName.toLowerCase())
You must use more than one search method :
queryGroups(groupName: string) {
this.groups = this.totalGroupsList.filter((group) => {
let isExist = this.searchFunc(groupName, group.userId)
|| this.searchFunc(groupName, group.dps)
|| this.searchFunc(groupName, group.sourceType)
if (isExist) {
return true;
} else {
let isRole = false;
group.role.forEach((role) => {
if (this.searchFunc(groupName, role.name)) {
isRole = true;
break;
}
});
return isRole !== false;
}
});
}
private searchFunc(searchKey, searchTarget): boolean {
if(!searchKey) {
return false;
}
return (searchTarget.toLocaleUpperCase().includes(searchKey.toLocaleUpperCase())) ||
(searchTarget.toUpperCase().includes(searchKey.toUpperCase())) ||
(searchTarget.includes(searchKey.toLocaleUpperCase())) ||
(searchTarget.includes(searchKey.toUpperCase())) ||
(searchTarget.toLocaleUpperCase().includes(searchKey)) ||
(searchTarget.toUpperCase().includes(searchKey)) ||
(searchTarget.includes(searchKey))
}

Updating Array from AsyncStorage

I have an array of objects called audioBaby.
When the app launches I check asyncStorage and if any key has value active, I want to update the lock keys in the array.
What I have done is not updating all objects in array but only the last object.
How can I initially update the array from asyncStorage and render the screen?
const [audioBaby, setAudioBaby] = useState([
{
lock: "deactive",
url: "item0.mp3",
},
{
lock: "deactive",
url: "item1.mp3",
},
{
lock: "deactive",
url: "item2.mp3",
},
]);
useEffect(() => {
try {
AsyncStorage.multiGet([
"babyAudio0Status", //value: active
"babyAudio1Status", //value: active
"babyAudio2Status", //value: active
]).then((response) => {
let updatedList = audioBaby;
if (response[0][1] != "null" && response[0][1] == "active") {
updatedList = audioBaby.map((item) => {
if (item.url == "item0.mp3") {
return { ...item, lock: "active" };
}
return item;
});
}
if (response[1][1] != "null" && response[1][1] == "active") {
updatedList = audioBaby.map((item) => {
if (item.url == "item1.mp3") {
return { ...item, lock: "active" };
}
return item;
});
}
if (response[2][1] != "null" && response[2][1] == "active") {
updatedList = audioBaby.map((item) => {
if (item.url == "item2.mp3") {
return { ...item, lock: "active" };
}
return item;
});
}
setAudioBaby(updatedList)
});
} catch (error) {
console.log("error::", error);
}
}, []);
Final array should be like this:
[
{
lock: "active",
url: "item0.mp3",
},
{
lock: "active",
url: "item1.mp3",
},
{
lock: "active",
url: "item2.mp3",
},
]
I moved all ifs to inside of map function and everything is fine.
let updatedList = audioBaby.map((item) => {
if (item.url === 'item0.mp3' && response[0][1] === 'active') {
return { ...item, lock: 'active' }
}
if (item.url === 'item1.mp3' && response[1][1] === 'active') {
return { ...item, lock: 'active' }
}
if (item.url === 'item2.mp3' && response[2][1] === 'active') {
return { ...item, lock: 'active' }
}
return item
})

Break Nested some or map JavaScript

PC = {a:{ID: "abc",options:{x1:"100", x2:"200"}},b:{ID: "d",options:{x2:"100", x3:"200"}}}
pro = {
"pro": [
{
"pID": "abc",
"attributes": {
"xyz": [
"1",
"2",
"3"
],
"foo": "フルプレミアム"
}
}
]
}
functionX() {
let isND = true;
if (pro === null || pro === [] || pro.length === 0) {
return isND;
} else if (pro.length > 0) {
some(PC, (p) => {
some(p.options, (o, k) => {
some(pro, (item) => {
if (p.ID === item.pID && k === 'xyz') {
if (item.attributes[k] !== []) {
isND = false;
}
} else if (p.ID === item.pID && k !== 'xyz') {
if (item.attributes[k] !== '') {
isND = false;
}
}
});
});
});
}
return isND;
}
I have to iterate through 3 different collections to check my condition and return a value. I am trying to exit the nested some or map if one of my if- else conditions satisfy. I tried passing return true after isND = false but doesn't work. Can someone help resolve this.
Array.prototype.some() will exit early if any of the callbacks return true so you could return the result that way.
It's not very clear but it seems you want to use this "early exit" feature while returning the inverse. How about something like this...
// ignoring "if (pro === null || pro === [] || pro.length === 0)" for this example
// return the inverse
return !Object.values(PC).some(({ ID, options }) => {
return Object.entries(options).some(([k, o]) => {
// here "k" is one of your "x1", "x2", etc keys
// and "o" is the corresponding value
return pro.pro.some(item => {
// return "true" if any of your "conditions" are met
})
})
})
return Object.values(PC).some(({ ID, options }) => {
return Object.entries(options).some(([k]) => {
return (pro.pro).some((item) => {
if (condition) {
if (condition) {
return false;
}
return true;
} else if (condition) {
if (condition) {
return false;
}
return true;
}
return null;
});
});
});
// Haven't returned the inverse of outer function

Filter an array which is a property of an object in an immutable way

How do I filter an array which is a property of an object in an immutable way?
For ex.
public transform(contactGroups: ContactGroup[], searchText: string): ContactGroup[] {
if (!contactGroups) {
return [];
}
if (searchText === undefined) {
return contactGroups;
}
return contactGroups.filter((contactGroup: ContactGroup) => {
return contactGroup.contacts.filter((contact: Contact) => {
return contact.displayName && contact.displayName.toLowerCase().includes(searchText.toLowerCase())
}).length > 0;
});
}
In above example, contactGroup.contacts contains all the items from the array but not the filtered result due object reference.
Any help would be appreciated.
Thank you.
function transform(contactGroups, searchText) {
if (!contactGroups) {
return [];
}
if (searchText === undefined) {
return contactGroups;
}
return contactGroups.filter(function (contactGroup) {
return contactGroup.contacts.filter(function (contact) {
return (contact.displayName && contact.displayName.toLowerCase().includes(searchText.toLowerCase()));
}).length > 0;
});
};
var contactGroups = [{
"letter":"S",
"contacts":[
{
"id":"173",
"rawId":null,
"displayName":"sam",
"name":{
"givenName":"sam",
"formatted":"sam"
},
"nickname":null,
"phoneNumbers":null,
"emails":[
{
"id":"955",
"pref":false,
"value":"sam#xyz.com",
"type":"other"
}
],
"addresses":null,
"ims":null,
"organizations":null,
"birthday":null,
"note":"",
"photos":null,
"categories":null,
"urls":null
},
{
"id":"1717",
"rawId":null,
"displayName":"Sat33",
"name":{
"givenName":"Sat33",
"formatted":"Sat33 "
},
"nickname":null,
"phoneNumbers":[
{
"id":"5521",
"pref":false,
"value":"1133",
"type":"work"
}
],
"emails":null,
"addresses":null,
"ims":null,
"organizations":null,
"birthday":null,
"note":null,
"photos":null,
"categories":null,
"urls":null
},
{
"id":"1712",
"rawId":null,
"displayName":"Server1234",
"name":{
"givenName":"Server1234",
"formatted":"Server1234 "
},
"nickname":null,
"phoneNumbers":[
{
"id":"5509",
"pref":false,
"value":"1234",
"type":"mobile"
}
],
"emails":null,
"addresses":null,
"ims":null,
"organizations":null,
"birthday":null,
"note":null,
"photos":null,
"categories":null,
"urls":null
}
]
}]
console.log(transform(contactGroups, 'ver'))
It should return contactGroup with only contact object 'Server1234' since the searched string is 'ver' but it still returns contactGroup with all contact object.
you can try this solution
class ContactGroup {
contacts: Contact[]
}
class Contact {
displayName: string
}
function transform(contactGroups: ContactGroup[], searchText: string): ContactGroup[] {
if (!contactGroups) {
return [];
}
if (searchText === undefined) {
return contactGroups;
}
return contactGroups.map((contactGroup: ContactGroup) => {
return {
...contactGroup,
contacts: contactGroup.contacts.filter((contact: Contact) => {
return contact.displayName && contact.displayName.toLowerCase().includes(searchText.toLowerCase())
})
}
}).filter((contactGroup: ContactGroup) => {
return contactGroup.contacts.length > 0
})
}
You can empty the passed array and push filtered elements into it. Here is a simplified version of your code:
function transform(contactGroups, searchText) {
var filtered = contactGroups.filter(e => e.name.includes(searchText));
contactGroups.splice(0, contactGroups.length);
contactGroups.push(...filtered);
return filtered; // <-- if still needed
}
var contacts = [{name: 'abc'}, {name: 'abcc'}, {name: 'xyz'}];
transform(contacts, 'abc');
console.log(contacts);

Categories

Resources