Undefined for firebase subscribe - javascript

I need to return array of items to display it on HomePage
I tried to modify the code, but nothing works. I feel like I need a slight change for my code
getItems(segmentType): any {
return this.db.collection('items', ref => ref.where('type', '==',
segmentType)).valueChanges();
}
getItemsBySearchQuery(segmentType, queryText): any[] {
this.getItems(segmentType).subscribe(items => {
this.itemsContainer = items;
this.filteredItems = this.itemsContainer.filter((v) => {
if (v.title && queryText) {
if (v.title.toLowerCase().indexOf(queryText.toLowerCase()) > -1) {
return true;
}
return false;
}
});
});
//TODO: THIS IS STILL UNDEFINED
return this.filteredItems;
}
Ion-List with filtered elements, but I have "undefined", because code returns the array too early

Related

LIVR Validate if element in object is empty array

I have LIVR in a project i'm working now and is quite unclear to me how this work. I can't understand how to create new rules for custom validation.
Here's the code:
LIVR.Validator.defaultAutoTrim(true);
let validator = new LIVR.Validator({});
LIVR.Validator.registerDefaultRules({
nested_object_value() {
return function (value) {
if (!value || (value && !value.value || value === [])) {
return 'REQUIRED';
}
return '';
};
},
max_number_advancement() {
return function (value) {
if (value > 100) {
return 'MAX_NUMBER';
}
return '';
};
},
required_if_activity_present() {
return function (value, allValue) {
if (allValue.activitycycletype && !value || allValue.requestpeople === []) {
console.log(first)
return 'REQUIRED_IF_CYCLETYPE';
}
return '';
};
},
});
And this is how its used:
validationForm = () => {
const { formValue, updateErrors } = this.props;
const validData = validator.validate(formValue);
console.log(formValue)
if (!validData) {
const errorsValidator = validator.getErrors();
if (errorsValidator && Object.keys(errorsValidator).length > 0) {
const newErrors = {};
Object.keys(errorsValidator).forEach((error) => {
newErrors[error] = errorsValidator[error];
});
updateErrors(newErrors);
}
blame(t('validation-error'));
return false;
}
updateErrors({});
return true;
}
Opening the form with this validation in the app, seems to call only the last method required_if_activity_present().
What i expect here is that i can create a new method inside registerDefaultRules(), that is a LIVR method, like this:
LIVR.Validator.registerDefaultRules({
re quired_not_empty() {
return function (value) {
if (!value) {
return 'REQUIRED';
}
return '';
};
},
... //other methods
}
but seems not working, the newer method is not being called at all by validator.validate()
Anyone know how to create a new rules where i can check if an element inside the object that has to be validate is an empty array?
Because seems that LIVR doesn't return a validation error in this case, but only on empty string and null values.
Thanks in advance

Array is undefined from Veux Store

I am retrieving data from the Vuex Store. I first of all want to check of the array is present in the Vuex Store, after that I want to check if the noProducts object at index 0 is not present.
The reason for this is that tweakwiseSortedProducts is used for both products and a no Products boolean to react to in the front-end
tweakwiseHasProducts () {
if (this.$store.state.tweakwise?.tweakwiseSortedProducts) {
return (
this.$store.state.tweakwise.tweakwiseSortedProducts[0].noProducts ===
false
);
}
return false;
},
My front-end currently, often, returns:
this.$store.state.tweakwise.tweakwiseSortedProducts[0] is undefined
In the console.
This happens because tweakwiseSortedProducts is not undified but an empty list. You can try:
tweakwiseHasProducts () {
if (this.$store.state.tweakwise?.tweakwiseSortedProducts?.length !== 0) {
return (
this.$store.state.tweakwise.tweakwiseSortedProducts[0].noProducts ===
false
);
}
return false;
},
or just:
tweakwiseHasProducts () {
return this.$store.state.tweakwise?.tweakwiseSortedProducts[0]?.noProducts === false;
},
which will be false if any of this elements is undefined, or true if noProducts is really false
It is recommended to use getter when calling a value in Vuex.
Please refer to the following.
getters: {
getTweakwiseSortedProducts: (state: any) => {
return state.tweakwise?.tweakwiseSortedProducts || [];
},
},
tweakwiseHasProducts () {
this.$store.getters.getTweakwiseSortedProducts.length ? true : false;
}

Validate Duplicate Data Entry in Array - JavaScript

My problem is that I want to insert values that are not repeated when doing a push
This is my code :
addAddress: function() {
this.insertAddresses.Adress = this.address_address
this.insertAddresses.State = this.selectedStateAddress
this.insertAddresses.City = this.selectedCityAddress
if(this.insertAddresses.Adress !== "" && this.insertAddresses.State !== null && this.insertAddresses.City !== null) {
let copia = Object.assign({}, this.insertAddresses);
this.addresses.push(copia)
}
else
{
this.$message.error('Not enough data to add');
return
}
},
When adding a new element to my object, it returns the following.
When I press the add button again, it adds the same values again, I want to perform a validation so that the data is not the same. How could I perform this validation in the correct way?
Verify that the item doesn't already exist in the array before inserting.
You can search the array using Array.prototype.find:
export default {
methods: {
addAddress() {
const newItem = {
Address: this.address_address,
State: this.selectedStateAddress,
City: this.selectedCityAddress
}
this.insertItem(newItem)
},
insertItem(item) {
const existingItem = this.addresses.find(a => {
return
a.State === item.State
&& a.City === item.City
&& a.Address === item.Address
})
if (!existingItem) {
this.addresses.push(item)
}
}
}
}
On the other hand, if your app requires better performance (e.g., there are many addresses), you could save a separate dictonary to track whether the address already exists:
export default {
data() {
return {
seenAddresses: {}
}
},
methods: {
insertItem(item) {
const { Address, State, City } = item
const key = JSON.stringify({ Address, State, City })
const seen = this.seenAddresses[key]
if (!seen) {
this.seenAddresses[key] = item
this.addresses.push(item)
}
}
}
}
demo
check it:
let filter= this.addresses.find(x=> this.insertAddresses.State==x.State)
if (filter==null) {
this.$message.error('your message');
}
OR FILTER ALL
let filter= this.addresses.find(x=> this.insertAddresses.Adress==x.Adress && this.insertAddresses.State==x.State && this.insertAddresses.City==x.City)
if (filter==null) {
this.$message.error('your message');
}
``

Why is my original state mutated when filtering with react redux

im using redux in an react app. Why is this filtering func mutating the original state.products? I cant understand why
state.products = [
{
type: "one",
products: [
{ active: true },
{ active: false }
]
}
]
function mapStateToProps(state) {
const test = state.products.filter((item) => {
if(item.type === "one") {
return item.products = item.products.filter((item) => {
item.active
});
}
return item;
});
return {
machineSearchWeightRange: state.machineSearchWeightRange,
filteredItems: test //This will have only products active
};
}
filteredItems will have only products that is active but the state.products is also updated containing only active products when trying to filter on the same data again.
Suggestions
Because you're assigning to a property on an existing state item:
function mapStateToProps(state) {
const test = state.products.filter((item) => {
if(item.type === "one") {
return item.products = item.products.filter((item) => { // <========== Here
item.active
});
}
return item;
});
return {
machineSearchWeightRange: state.machineSearchWeightRange,
filteredItems: test //This will have only products active
};
}
Instead, create a new item to return. Also, it looks like you need map along with filter, and you're not actually returning item.active in your inner filter (see this question's answers for more there):
function mapStateToProps(state) {
const test = state.products.filter(({type}) => type === "one").map(item => {
return {
...item,
products: item.products.filter((item) => {
return item.active;
})
};
});
return {
machineSearchWeightRange: state.machineSearchWeightRange,
filteredItems: test //This will have only products active
};
}
Side note: This:
products: item.products.filter((item) => {
return item.active;
})
can be simply:
products: item.products.filter(({active}) => active)

Vue JS filter results based on checkbox array

I've built a Vue JS search component to search and filter a list of properties for a property website. The search component is listed on every page, so it makes sense for me to use a URL search query which takes me to the main properties page and then use something like this.$route.query.search to get the value from my query and store in a variable.
The property data is coming from a JSON file which essentially looks like this:
{
"data": [
{
"id": 12,
"sold": false,
"isFeatured": true,
"slug": "green-park-talbot-green-cf72-8rb",
"address": "Green Park, Talbot Green CF72 8RB",
"county": "Rhondda Cynon Taf",
"price": "695000",
"features": ["Modern fitted kitchen", "Integrated appliances", "Front and rear gardens"],
"type": "Semi-Detached",
"bedrooms": "3"
}
}
My search query would be something like this:
/properties/?search=Address%20Here&type=Apartment&bedrooms=2&county=Maesteg
Which then would filter each thing.
How this works is quite simple, inside my data object I have my variables which get each query and store them as follows:
data () {
return {
searchAddress: this.$route.query.search,
searchType: this.$route.query.type,
searchBedrooms: this.$route.query.bedrooms,
searchCounty: this.$route.query.county
}
}
And then I have a filter inside the computed area called filteredProperties which filters down the properties inside the v-for which isn't necessary to show here:
computed: {
filteredProperties: function(){
return this.properties.filter((property) => {
return property.address.match(this.searchAddress) && property.type.match(this.searchType) && property.bedrooms.match(this.searchBedrooms) && property.county.match(this.searchCounty)
});
}
}
Now this works absolutely fine and works correctly... however I now need to modify this to instead of having <select> dropdowns which is how you would currently pick the number of bedrooms, or the property type etc, I now need to replace the property type <select> dropdown with checkboxes so that the user can select multiple property types and essentially add that as an array into the URL.
I'm not quite sure how to modify this part of my filter to be able to look for multiple property types:
property.type.match(this.searchType)
Many thanks
UPDATE
I've recently tried updating my computed filter with the following:
computed: {
filteredProperties: function(){
return this.properties.filter((property) => {
return property.address.match(this.searchAddress) &&
this.searchAddress.some(function(val){
return property.search.match(val)
}) &&
property.type.match(this.searchType) &&
this.searchType.some(function(val){
return property.type.match(val)
}) &&
property.bedrooms.match(this.searchBedrooms) &&
this.searchBedrooms.some(function(val){
return property.bedrooms.match(val)
}) &&
property.county.match(this.searchCounty) &&
this.searchCounty.some(function(val){
return property.county.match(val)
})
});
}
}
I need the search to work with and without a URL query.
Also tried an if/else statement:
computed: {
filteredProperties: function(){
return this.properties.filter((property) => {
return property.address.match(this.searchAddress) &&
if (this.searchType.length > 1) {
this.searchType.some(function(val){
return property.type.match(val)
})
} else {
property.type.match(this.searchType)
} &&
property.bedrooms.match(this.searchBedrooms) &&
property.county.match(this.searchCounty)
});
}
}
UPDATE
I got it working by doing the following:
computed: {
filteredProperties: function(){
return this.properties.filter((property) => {
let searchTypeMatch;
if (typeof this.searchType === "object") {
searchTypeMatch = this.searchType.some(function(val){
return property.type.match(val)
})
} else {
searchTypeMatch = property.type.match(this.searchType)
}
return property.address.match(this.searchAddress) &&
searchTypeMatch &&
property.bedrooms.match(this.searchBedrooms) &&
property.county.match(this.searchCounty)
});
}
}
You will have to use JSON for the query parameters in order to serialize/deserialize the arrays.
data () {
return {
searchAddress: this.$route.query.search ? JSON.parse(this.$route.query.search) : [],
searchType: this.$route.query.type ? JSON.parse(this.$route.query.type) : [],
searchBedrooms: this.$route.query.bedrooms ? JSON.parse(this.$route.query.bedrooms) : [],
searchCounty: this.$route.query.county ? JSON.parse(this.$route.query.county) : []
}
}
computed: {
filteredProperties: function()
{
return this.properties.filter((property) =>
{
return (this.searchAddress.length ? this.searchAddress.some((address) =>
{
return property.address.match(address);
}) : true) && (this.searchType.length ? this.searchType.some((type) =>
{
return property.type.match(type);
}) : true) && (this.searchBedrooms.length ? this.searchBedrooms.some((bedrooms) =>
{
return property.bedrooms.match(bedrooms);
}) : true) && (this.searchCounty.length ? this.searchCounty.some((county) =>
{
return property.county.match(county);
}) : true)
});
}
}
Then you send query params like this
this.$router.push("/search?search=" + JSON.stringify(searchArray)
+ "&type=" + JSON.stringify(typeArray)
+ "&bedrooms=" + JSON.stringify(bedroomsArray)
+ "&county=" + JSON.stringify(countyArray)
);
I have not worked with routing in Vue apps but for the following to work you will have to ensure that this.$route.query.search (and the other route properties) is an (are) [](s).
return this.searchAddress.some(function(val) {
return property.address.match(val)
}) &&
this.searchType.some(function(val){
return property.type.match(val)
}) && ...
Let me know if this works for you.
RE-EDITED:
Hi, please change the computed property to the following
computed: {
filteredProperties: function () {
let self = this
let routeConstraints = ['search', 'type', 'bedrooms', 'county'].filter(function (val) {
return self.$route.query[val] !== undefined
})
if (routeConstraints.length === 0) {
return self.properties
} else {
return routeConstraints.reduce(function (acc, val) {
return acc.filter(function (property) {
//basically I am checking if there is some value in the query parameter that matches properties.
if (self.$route.query[val] !== undefined) {
//check if the route parameter is an array (object)
if (typeof this.searchType === "object") {
self.$route.query[val] = [self.$route.query[val]]
}
}
return self.$route.query[val].some(function (item) {
//changed the matching condition to indexOf
return property[val].match(item).length > 0
})
})
}, self.properties)
}
}
}
Basically,
I am trying to check what routes values are set from your checkbox selections
Using it to filter the properties array.
If none are set then all properties are returned.
Hope this works.

Categories