How do I resolve a callback error with 'callback' is an instance of Object)? - react-native

TypeError: callback is not a function. (In 'callback(data)',
'callback' is an instance of Object)
The code here works just fine when I write it like this:
const onSelectFilterDone = (filter) => {
setFilter(filter);
setFilterModalVisible(false);
unsubscribe.current = listingsAPI.subscribeListings(
{ categoryId: category.id },
// { categoryId2: category2.id },
favorites,
onListingsUpdate,
);
};
When i uncomment that other line, it breaks and gives me this error.
const onSelectFilterDone = (filter) => {
setFilter(filter);
setFilterModalVisible(false);
unsubscribe.current = listingsAPI.subscribeListings(
{ categoryId: category.id },
{ categoryId2: category2.id },
favorites,
onListingsUpdate,
);
};
Here is the relevant snippet from listingsAPI (below) if it helps but this code works fine when there is only one object. Is there a specific way to make this work with two objects like above?
if (categoryId) {
return (
listingsRef
.where('categoryID', '==', categoryId)
.where('isApproved', '==', isApproved)
.onSnapshot((querySnapshot) => {
const data = [];
querySnapshot.forEach((doc) => {
const listing = doc.data();
if (favorites && favorites[doc.id] === true) {
listing.saved = true;
}
data.push({ ...listing, id: doc.id });
});
callback(data);
})
);
}
if (categoryId2) {
return (
listingsRef
.where('categoryID2', '==', categoryId2)
.where('isApproved', '==', isApproved)
.onSnapshot((querySnapshot) => {
const data = [];
querySnapshot.forEach((doc) => {
const listing = doc.data();
if (favorites && favorites[doc.id] === true) {
listing.saved = true;
}
data.push({ ...listing, id: doc.id });
});
callback(data);
})
);
}

You can combine your queries via this way if you want to have it optional:
let query = listingsRef.where('isApproved', '==', isApproved)
if (categoryId) {
query = query.where('categoryID', '==', categoryId)
}
if (categoryId2) {
query = query.where('categoryID2', '==', categoryId2)
}
query.onSnapshot...

Related

multiple select data in object format

I have a multiple select field where I'll be selecting multiple values, but when I am sending that data to the backend it should show in the following format:
"data":
[
{
"vehicle_id": "VEH1",
},
{
"vehicle_id": "VEH2",
},
]
but when I am selecting multiple values from drop down I am getting data in an array format:
"data":[
{
"vehicle_id":["VEH1","VEH2"]
}
]
How can I send data in the format which I have added in the beginning? .
Code:
const getSelectedVehices = (selectedvehicles: any[]) => {
const vehicles: Array<string> = [];
const items = new Map<string, string>();
vehicleListData.forEach((item) => {
items.set(item.vehicleName, item.vehicleAliasId);
});
selectedvehicles.forEach((item) => {
vehicle.push(items.get(item) || '');
});
return vehicles;
};
const prepareSelectedVehiclesServices = (electedvehicles: any[]) => {
const vehicles: Array<string> = [];
const items = new Map<string, string>();
vehicleListData.forEach((item) => {
items.set(item.vehicleName, item.vehicleAliasId);
});
vehicles.forEach((item) => {
if (items.has(item)) {
vehicles.push(items.get(item) || '');
}
});
return vehicles;
};
<MultiSelect
items={pickerOptions.vehicleServices}
onSelectedItemsChange={(Ids: any[]) => {
const selectedVehiclesServices = getSelectedVehicles(Ids);
formikData.setFieldValue(`vehicles`, [
{
vehicleAliasId: selectedVehiclesServices,
},
]);
}}
selectedItems={{
selectedItemIdentifiers: prepareSelectedVehiclesServices(
formikData.values.services || initialServiceValues.services,
),
}}
></MultiSelect>
the above is the code which I have added.
Just project the array into your new format with .map(). Something like this:
let myData = { "data":[
{
"vehicle_id":["VEH1","VEH2"]
}
]};
let myNewData = { "data": myData.data[0].vehicle_id.map(d => ({
"vehicle_id": d
}))};
console.log(myNewData);

Vue js - not all the data showing after store dispatch

The select box not showing sometimes the first color and sometimes not showing the first color.
How can i make it to show all the item in the select box?
I'm not getting for some reason all the promises
You can see the issue in the picture
Please help me to fix this issue i'm new to vue js
My code:
data() {
return {
propertiesTree: []
}
}
getPropertyGroups(objectId: number): void {
if (this.$data.currentObjectId === objectId)
return;
let component: any = this;
this.$data.currentObjectId = objectId;
component.showLoader();
this.$store.dispatch('properties/getPropertyGroups', objectId)
.then(({ data, status }: { data: string | Array<propertiesInterfaces.PropertyGroupDto>, status: number }) => {
// console.log(data, "data");
// console.log(status, "status")
if (status === 500) {
this.$message({
message: data as string,
type: "error"
});
}
else {
let anyData = data as any;
anyData.map(item => {
item.properties.map(prop => {
if(prop.type.toString() === 'dictionary'){
prop.dictionaryList = [];
prop.color = '';
this.getWholeDictionaryList(prop.dictionaryId.value, prop)
}
});
});
}
component.hideLoader();
});
},
getWholeDictionaryList(dictionaryId: number, prop: any){
this.$store.dispatch('dictionaries/getWholeDictionaryList', dictionaryId).then(
({ data, status }: { data: Array<any> |string , status: number }) => {
if (status === 500) {
this.$message({
message: data as string,
type: "error"
});
} else {
const arrData = data as Array<any>;
arrData.map((item,index) => {
prop.dictionaryList = [];
prop.dictionaryList = data;
this.getDictionaryItemColor(item.id.value, data, index, prop);
});
}
});
},
getDictionaryItemColor(dictionaryItemId:number, dictionaryList: Array<any>, index:number, current){
this.$store.dispatch('patterns/getDictionaryItemColor', dictionaryItemId).then((data: any, status: number) => {
if (status === 500) {
this.$message({
message: data as string,
type: "error"
});
} else{
debugger
if(current.dictionaryItemId.value === data.data.sceneObjectId)
current.color = data.data.colorString;
dictionaryList[index].color = data.data.colorString ? data.data.colorString: '#FFFFFF';
}
});
},
Html code of the select box
<el-select v-model="data.color" placeholder="Select">
<el-option
v-for="item in data.dictionaryList"
:key="item.name"
:label="item.color"
:value="item.color">
</el-option>
</el-select>
I did return to dispatch
let dispatch = this.getWholeDictionaryList(prop.dictionaryId.value, prop)
let promiseArr = [];
promiseArr.push(dispatch);
after the map closing tag i did
Promise.all(promisArr).then( () => {
debugger
this.$data.propertiesTree = anyData;
});
And I've got it solved

React Native Redux issue

I am having an issue with adding favourite functionality for e-commerce app. Getting error of undefined.enter image description here
case TOGGLE_FAVOURITE:
const exitsIndex = state.favouriteProducts.findIndex((meal) => meal.id === action.productId);
if(exitsIndex >= 0) {
return { ...state, favouriteProducts: state.favouriteProducts.filter((meal) => meal.id !== action.productId) }
} else {
const favMeal = state.availableProducts.find((meal) => meal.id === action.productId);
return { ...state, favouriteProducts: state.favouriteProducts.concat(favMeal) };
}
This is my action:
export const toggleFavourite = id => {
return { type: TOGGLE_FAVOURITE, productId: id };
};
And this is my call function:
const toggleFavouriteHandler = useCallback(() => {
dispatch(toggleFavourite(productId));
}, [dispatch, productId]);
you have to check for the initial state, when you are doing findIndex on favouriteProducts , favouriteProducts is null.
so just check if
state.favouriteProducts === null and that should work
To prevent TypeError you should check if state.favouriteProducts is undefined or null.
In this case, i would use:
case TOGGLE_FAVOURITE:
if (!state.favouriteProducts) return false; // you need this
const exitsIndex = state.favouriteProducts.findIndex((meal) => meal.id === action.productId);
if (exitsIndex >= 0) {
return { ...state, favouriteProducts: state.favouriteProducts.filter((meal) => meal.id !== action.productId) }
} else {
const favMeal = state.availableProducts.find((meal) => meal.id === action.productId);
return { ...state, favouriteProducts: state.favouriteProducts.concat(favMeal) };
}
I found different solution. Now its working
case TOGGLE_FAVOURITE:
const addedFavourite = action.product;
const id = addedFavourite.id;
const product_name = addedFavourite.product_name;
const product_image = addedFavourite.product_image;
const product_description = addedFavourite.product_description;
const product_price = addedFavourite.product_price;
const category_id = addedFavourite.category_id;
let updatedFavouriteItem = new Product(
id,
product_name,
product_image,
product_description,
product_price,
category_id,
)
if(state.items[addedFavourite.id] != null){
let updatedCartItems = { ...state.items };
delete updatedCartItems[action.product.id];
return {
...state,
items: updatedCartItems,
}
}
return{
...state,
items: {...state.items, [addedFavourite.id]: updatedFavouriteItem }
}
}
return state;
}

React Native SectionList (title, data) - Search in the data field

I am trying to build Search function in SectionList. I have search inside the 'data' (second field) and not inside 'title' but I am not able to make it work.
My Data is about the Flat / resident details of an Apartment -
sectiondata =
[{"title":"GROUND FLOOR",
"data":[
{"id":"48","res_type":"owner","user_name":"Ashwani","flat_id":"1","flat_name":"001","floor_no":"GROUND FLOOR","floor_int":"0","signal_player_id":"aa","user_phone":"98855550"},
{"id":"49","res_type":"owner","user_name":"Rahul","flat_id":"2","flat_name":"002","floor_no":"GROUND FLOOR","floor_int":"0","signal_player_id":"aa","user_phone":"999999"}
]
}]
I am trying something like this but it is not working.
searchFilterFunction = (text) => {
let search = text.toLowerCase();
this.setState({
check: this.state.sectiondata.filter(
obj => obj.data['flat_name'].toLowerCase().includes(search))
});
}
How to filter data base on name? Please assist here.
Thanks.
You can try to search like this:
onChangeText(text) {
if (text.trim().length > 0) {
var temp = []
sectiondata.map((item) => {
var dataItem = {};
var brandData = [];
item.data.map((searchItem) => {
let flatName = searchItem.flat_name
if (flatName.match(text)) {
brandData.push(searchItem);
}
})
if (brandData.length > 0) {
} else {
return null;
}
dataItem.brandData = brandData;
temp.push(dataItem);
this.setState({
sectiondata: temp
})
})
} else {
this.setState({
sectiondata: this.state.tempData
})
}
}
searchFilterFunction(text) {
if( text == undefined || text == '') {
this.setState({
sectiondata: this.arrayholder
})
return;
}
if (text.trim().length > 0) {
var temp = []
this.state.sectiondata.map((item) => {
var dataItem = {};
var title = item.title;
var brandData = [];
item.data.map((searchItem) => {
let flatName = searchItem.flat_name
if (flatName.match(text)) {
brandData.push(searchItem);
}
})
if (brandData.length > 0) {
} else {
return null;
}
dataItem.title = title;
dataItem.data = brandData;
temp.push(dataItem);
this.setState({
sectiondata: temp
})
})

I am getting this error ,"value for message cannot be cast from double to string"

I am getting this error when I am trying pass object to axios method "value for message cannot be cast from double to string". Does any one have Idea about this.
I have added my two functions.
addNotes = (formData) => {
let noteText = ''
Object.keys(formData).map((item) => {
noteText += formData[item] !== undefined ? `${formData[item]} \n` : ``
})
let localLocation = `${this.state.localAddress.locality}, ${this.state.localAddress.subLocality}`
let { userMetaData, graphListlimit, graphListoffset, imdCode } = this.state
let obj = {
'edEmployeeCode': userMetaData.ed_employee_code,
'edName': userMetaData.ed_name,
'edRoleCode': userMetaData.ed_role_code,
'imdCode': imdCode,
'imdSegment': null,
'bnNoteText': noteText,
'location': localLocation,
'meetingType': this.state.meetingType
}
this.props.onAddNotesAction(obj)
}
export const addNotesAction = (obj) => {
let params = {
ed_employee_code: obj.empCode,
ed_role_code: obj.empRoleCode,
ed_channel: obj.empChannel,
ed_name: obj.edName,
imd_code: obj.imdCode,
imd_segment: null,
bn_note_text: obj.bnNoteText,
location: obj.location,
meeting_type: obj.meetingType
}
return dispatch => {
axios.defaults.headers.common['Authorization'] = obj.token;
axios.post(`${Config.apiRootPath}/meetings/addbranchnote`,
params,
).then(response => {
dispatch(addNotesSuccess(response));
}).catch(err => {
dispatch(addNotesFailure(err.response));
});
};
};