multiple select data in object format - react-native

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);

Related

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

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...

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 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
})
})

How to unit test API calls with axios() in react-native with Jest

I am developing Sample Application in React-native . I used Jest to use unit testing, i don't have an idea about Jest Api call
I want to need without using Promises:
Here this is my Code:
this is My Function Code:
/**
* #description Action to call nilpick service ,on success increment route as well as mark the location as fulfilled
*/
function nilPick() {
return async (dispatch, getState) => {
const currentState = getState();
const { user, picking } = currentState;
const { currentRouteIndex, pickRoute } = getState().picking.pickRouteInfo;
const { workId } = picking.pickWorkInfo;
const nilPickItem = pickRoute[currentRouteIndex];
const currentItem = getCurrentItem(currentState);
const currentTime = dateFunctions.getCurrentUTC();
const nilpickedItem = [
{
orderId: nilPickItem.fulfillOrdNbr,
lineNbr: nilPickItem.ordLine,
pickUpcNbr: nilPickItem.upc,
pickDisplayTs: currentTime,
pickUom: currentItem.workDetail.uom,
pickedLoc: nilPickItem.location,
locationType: nilPickItem.locType,
locId: nilPickItem.locId,
pickByType: currentItem.workDetail.pickByType,
exceptionPick: false,
gtinPrefRankNbr: 0,
pickUpcTypeCd: 5100
}
];
const { status, statusText } = await pickingService.nilPick(nilpickedItem, user, workId);
if (status === 200 || statusText === 'Created') {
console.info('Item nilpicked');
if (currentRouteIndex < pickRoute.length) {
dispatch(incrementRoute());
} else {
Alert.alert(
'Nilpick Complete',
[
{
text: 'OK',
onPress: () => {
dispatch(endPicking());
}
}
],
{ cancelable: false }
);
console.log('End of pickwalk');
return;
}
} else {
console.info('error in nilpicking item ');
}
};
}
This is my code above method to Converting Like this below sample test Case:
This is sample Test i want to call Api How to implement in Jest
it('Test For nillPic', () => {
const initialState = {
picking: {
pickRouteInfo: {
"fulfillOrdNbr": pickRouteInfo.fulfillOrdNbr,
"orderLine": '1',
"upc": '4155405089',
"location": 'A-1-1',
"availableLocsToPick": '2',
'suggSubPendingPicks?': 'N',
'manualSubPendingPicks?': 'N',
"lineFullfilled": 'false',
"currentRouteIndex": 1,
"pickRoute": ['r1', 'r2', 'r3']
}
}
};
// console.log("state data...", initialState);
const store = mockStore(initialState);
store.dispatch(actions.pickRouteActions.nilPickSuccess());
const expectedAction = [{ type: 'INCREMENT_ROUTE' }];
const localActions = store.getActions();
expect(localActions).toEqual(expectedAction);
});
Finally This is my code Please . Thanks in Advance

How to join two collections in a json store?

I am working on IBM Worklight. I need to access data from two collections. Is there any solution for joining the 2 collections and get the required fields ?
JSONSTORE does not have the ability to combine collections.
However the follow blog post details one way to achieve this: https://mobilefirstplatform.ibmcloud.com/blog/2015/02/24/working-jsonstore-collections-join/
Create a collection:
var OrdersCollection = {
orders: {
searchFields: {
order_id: 'integer',
order_date: 'string'
},
additionalSearchFields: {
customer_id: 'integer'
}
}
};
var CustomerCollection = {
customers: {
searchFields: {
customer_name : 'string',
contact_name : 'string',
country : 'string'
},
additionalSearchFields : {
customer_id : 'integer'
}
}
};
Add data using additional search fields:
var data = [
{order_id : 462, order_date : '1-1-2000'},
{order_id: 608, order_date : '2-2-2001'},
{order_id: 898, order_date : '3-3-2002'}
];
var counter = 0;
var q = async.queue(function (task, callback) {
setTimeout(function () {
WL.JSONStore.get('orders').add(task.data, {additionalSearchFields: {customer_id: task.customer_id}});
callback(++counter);
},0);
},1);
for(var i = 0; i < data.length; i++){
q.push({data : data[i], customer_id: i+1}, function(counter){
console.log("Added Order Doc " + counter);
});
}
q.drain = function(){
setTimeout(function() {
console.log("Finished adding order documents");
WL.JSONStore.get("orders").findAll({filter : ["customer_id", "order_id", "order_date"]})
.then(function (res) {
ordersCollectionData = res;
document.getElementById("orders").innerHTML = JSON.stringify(res, null, "\t");
})
.fail(function (err) {
console.log("There was a problem at " + JSON.stringify(err));
});
},0);
};
Find the documents to merge:
WL.JSONStore.get('orders').findAll({filter : ['customer_id', 'order_id', 'order_date']})
.then(function (res) {
ordersCollectionData = res;
});
Merge
var shared_index = 'customer_id';
var mergedCollection = [];
mergedCollection =_.merge(customerCollectionData, ordersCollectionData, function(a, b){
if(_.isObject(a) && (a[shared_index] == b[shared_index])) {
return _.merge({}, a, b);
}
});