In React-native i'm using 'sharingan-rn-modal-dropdown'; Dropdown in form for add and edit data but selected values not getting reflected in dropdown - react-native

what exactly is happening is when i select the delivery service onChangeService i'm setting the next dropdown i.e. carrier's list.Also i'm setting the selected carrier as per the service.But all the time value is getting set correctly in {this.state.selectedCarrierName} but still i can show its label only.lists contain label an value pair
async onChangeService(value) {
//{ ...this.props.deliveryOptionsValue, selected: value.value === value }
this.setState({ newCarrierList: [], selectedCarrierName: '', selectedCararierName: '' });
const priceDeliveryService = this.props.orderDetailsDTO.priceDeliveryServiceDTOs;
console.log("carriers", JSON.stringify(this.props.carriers));
var newList = [];
var carrier = '';
await priceDeliveryService.forEach(m => {
console.log("compare", m.serviceId === value.id);
if (m.serviceId === value.id) {
console.log("carrier", JSON.stringify(this.props.carriers));
let l = this.props.orderDetailsDTO.carriers.filter(n => n.id === m.carrierId);
console.log("l", l);
if (l !== undefined) {
// / orderList: [...this.state.orderList, ...content]
// this.setState({ newCarrierList: [...this.state.newCarrierList, ...l[0]] });
newList.push(l[0]);
console.log("defa", newList);
if (m.defaultCarrierService) {
this.setState({ selectedCarrier: l[0], selectedCarrierName: l[0].name });
carrier = l[0].name;
} else {
this.setState({ selectedCarrier: newList[0], selectedCarrierName: newList[0].name });
carrier = newList[0].name;
}
}
}
});
const list = newList.map(item => ({
label: item.name,
value: item
}));
this.setState({ newCarrierListValue: list, newCarrierList: newList })
console.log("newCarrierListValue", list);
console.log("newCarrierList", newList);
// console.log("carrier service", p.carrierName, value.id);
const carrierServices = this.props.orderDetailsDTO.carrierServiceDTO;
console.log(carrierServices.length);
const pi = await this.setCarrierService(carrierServices, value, carrier);
// let pi;
// for (let i = 0; i < carrierServices.length; i++) {
// console.log("if", carrierServices[i].cdlServiceId == value.id, carrierServices[i].carrierName === carrier)
// if (carrierServices[i].cdlServiceId == value.id && carrierServices[i].carrierName === carrier) {
// console.log("mathced data", carrierServices[i]);
// pi = carrierServices[i];
// console.log(pi);
// break;
// }
// }
this.setState({ carrierService: pi.serviceName, carrierServices: carrierServices });
console.log(pi.serviceName);
}
<Dropdown required
label="Select delivery option"
data={this.props.deliveryOptionsValue}
// enableSearch
defaultValue={1}
value={this.state.selectedDeliveryOptionName}
onChange={(value) => {
console.log(" change value", value);
this.setState({ selectedDeliveryOptionName: value.name, selectedDeliveryOption: value, deliveryOptionError: false, });
this.onChangeService(value);
}} />
<Dropdown
required
label="Select a carrier"
data={this.state.newCarrierListValue}
// selectedValue={this.state.selectedCarrierName}
value={this.state.selectedCarrierName}
onChange={value => {
// console.log("value", value);
this.setState({ selectedCarrierName: value.name, selectedCarrier: value });
this.onChangeCarrier(value, this.state.selectedDeliveryOption);
}} />

Related

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

How to change the width of NormalPeoplePicker dropdown

I'm using default example of NormalPeoplePicker from https://developer.microsoft.com/en-us/fluentui#/controls/web/peoplepicker#IPeoplePickerProps.
When the dropdown displays it cuts off longer items (example: 'Anny Lundqvist, Junior Manager of Soft..'). How do I make it wider, so that the full item's text displays?
import * as React from 'react';
import { Checkbox } from 'office-ui-fabric-react/lib/Checkbox';
import { IPersonaProps } from 'office-ui-fabric-react/lib/Persona';
import { IBasePickerSuggestionsProps, NormalPeoplePicker, ValidationState } from 'office-ui-fabric-react/lib/Pickers';
import { people, mru } from '#uifabric/example-data';
const suggestionProps: IBasePickerSuggestionsProps = {
suggestionsHeaderText: 'Suggested People',
mostRecentlyUsedHeaderText: 'Suggested Contacts',
noResultsFoundText: 'No results found',
loadingText: 'Loading',
showRemoveButtons: true,
suggestionsAvailableAlertText: 'People Picker Suggestions available',
suggestionsContainerAriaLabel: 'Suggested contacts',
};
const checkboxStyles = {
root: {
marginTop: 10,
},
};
export const PeoplePickerNormalExample: React.FunctionComponent = () => {
const [delayResults, setDelayResults] = React.useState(false);
const [isPickerDisabled, setIsPickerDisabled] = React.useState(false);
const [mostRecentlyUsed, setMostRecentlyUsed] = React.useState<IPersonaProps[]>(mru);
const [peopleList, setPeopleList] = React.useState<IPersonaProps[]>(people);
const picker = React.useRef(null);
const onFilterChanged = (
filterText: string,
currentPersonas: IPersonaProps[],
limitResults?: number,
): IPersonaProps[] | Promise<IPersonaProps[]> => {
if (filterText) {
let filteredPersonas: IPersonaProps[] = filterPersonasByText(filterText);
filteredPersonas = removeDuplicates(filteredPersonas, currentPersonas);
filteredPersonas = limitResults ? filteredPersonas.slice(0, limitResults) : filteredPersonas;
return filterPromise(filteredPersonas);
} else {
return [];
}
};
const filterPersonasByText = (filterText: string): IPersonaProps[] => {
return peopleList.filter(item => doesTextStartWith(item.text as string, filterText));
};
const filterPromise = (personasToReturn: IPersonaProps[]): IPersonaProps[] | Promise<IPersonaProps[]> => {
if (delayResults) {
return convertResultsToPromise(personasToReturn);
} else {
return personasToReturn;
}
};
const returnMostRecentlyUsed = (currentPersonas: IPersonaProps[]): IPersonaProps[] | Promise<IPersonaProps[]> => {
return filterPromise(removeDuplicates(mostRecentlyUsed, currentPersonas));
};
const onRemoveSuggestion = (item: IPersonaProps): void => {
const indexPeopleList: number = peopleList.indexOf(item);
const indexMostRecentlyUsed: number = mostRecentlyUsed.indexOf(item);
if (indexPeopleList >= 0) {
const newPeople: IPersonaProps[] = peopleList
.slice(0, indexPeopleList)
.concat(peopleList.slice(indexPeopleList + 1));
setPeopleList(newPeople);
}
if (indexMostRecentlyUsed >= 0) {
const newSuggestedPeople: IPersonaProps[] = mostRecentlyUsed
.slice(0, indexMostRecentlyUsed)
.concat(mostRecentlyUsed.slice(indexMostRecentlyUsed + 1));
setMostRecentlyUsed(newSuggestedPeople);
}
};
const onDisabledButtonClick = (): void => {
setIsPickerDisabled(!isPickerDisabled);
};
const onToggleDelayResultsChange = (): void => {
setDelayResults(!delayResults);
};
return (
<div>
<NormalPeoplePicker
// eslint-disable-next-line react/jsx-no-bind
onResolveSuggestions={onFilterChanged}
// eslint-disable-next-line react/jsx-no-bind
onEmptyInputFocus={returnMostRecentlyUsed}
getTextFromItem={getTextFromItem}
pickerSuggestionsProps={suggestionProps}
className={'ms-PeoplePicker'}
key={'normal'}
// eslint-disable-next-line react/jsx-no-bind
onRemoveSuggestion={onRemoveSuggestion}
onValidateInput={validateInput}
removeButtonAriaLabel={'Remove'}
inputProps={{
onBlur: (ev: React.FocusEvent<HTMLInputElement>) => console.log('onBlur called'),
onFocus: (ev: React.FocusEvent<HTMLInputElement>) => console.log('onFocus called'),
'aria-label': 'People Picker',
}}
componentRef={picker}
onInputChange={onInputChange}
resolveDelay={300}
disabled={isPickerDisabled}
/>
<Checkbox
label="Disable People Picker"
checked={isPickerDisabled}
// eslint-disable-next-line react/jsx-no-bind
onChange={onDisabledButtonClick}
styles={checkboxStyles}
/>
<Checkbox
label="Delay Suggestion Results"
defaultChecked={delayResults}
// eslint-disable-next-line react/jsx-no-bind
onChange={onToggleDelayResultsChange}
styles={checkboxStyles}
/>
</div>
);
};
function doesTextStartWith(text: string, filterText: string): boolean {
return text.toLowerCase().indexOf(filterText.toLowerCase()) === 0;
}
function removeDuplicates(personas: IPersonaProps[], possibleDupes: IPersonaProps[]) {
return personas.filter(persona => !listContainsPersona(persona, possibleDupes));
}
function listContainsPersona(persona: IPersonaProps, personas: IPersonaProps[]) {
if (!personas || !personas.length || personas.length === 0) {
return false;
}
return personas.filter(item => item.text === persona.text).length > 0;
}
function convertResultsToPromise(results: IPersonaProps[]): Promise<IPersonaProps[]> {
return new Promise<IPersonaProps[]>((resolve, reject) => setTimeout(() => resolve(results), 2000));
}
function getTextFromItem(persona: IPersonaProps): string {
return persona.text as string;
}
function validateInput(input: string): ValidationState {
if (input.indexOf('#') !== -1) {
return ValidationState.valid;
} else if (input.length > 1) {
return ValidationState.warning;
} else {
return ValidationState.invalid;
}
}
/**
* Takes in the picker input and modifies it in whichever way
* the caller wants, i.e. parsing entries copied from Outlook (sample
* input: "Aaron Reid <aaron>").
*
* #param input The text entered into the picker.
*/
function onInputChange(input: string): string {
const outlookRegEx = /<.*>/g;
const emailAddress = outlookRegEx.exec(input);
if (emailAddress && emailAddress[0]) {
return emailAddress[0].substring(1, emailAddress[0].length - 1);
}
return input;
}
Component which renders suggestion list have fixed width of 180px. Take a look at PeoplePickerItemSuggestion.styles.ts.
What you can do is to modify this class .ms-PeoplePicker-Persona:
.ms-PeoplePicker-Persona {
width: 260px; // Or what ever you want
}
UPDATE - Solution from comments
Change width trough styles property of PeoplePickerItemSuggestion Component
const onRenderSuggestionsItem = (personaProps, suggestionsProps) => (
<PeoplePickerItemSuggestion
personaProps={personaProps}
suggestionsProps={suggestionsProps}
styles={{ personaWrapper: { width: '100%' }}}
/>
);
<NormalPeoplePicker
onRenderSuggestionsItem={onRenderSuggestionsItem}
pickerCalloutProps={{ calloutWidth: 500 }}
...restProps
/>
Working Codepen example
For more information how to customize components read Component Styling.

Change value after confirmation in input VUE-JS

I have a table with an input column. This input column will have value if it has been saved in ddbb before.
If this value changes, handled with an event '#blur', I show a modal to confirm the change.
My problem is that if you want to keep the old value it will always change...
I tried to change this value with javascript, but it doesn't work... Any suggestions?
This is my code:
<b-tbody>
<b-tr
v-for="(driver, index) in drivers"
:key="driver.clientId">
<b-td
data-label="Client"
:title="driver.clientName">{{ driver.clientName }}</b-td>
<b-td data-label="Numerator">
<b-input
:id="'numeratorDriver_'+index"
class="driver-numerator text-right"
type="text"
:value="(driver.driverNumerator === undefined) ? 0 : $utils.formatNumber(driver.driverNumerator)"
#blur="calculatePricingDriver($event, index)" /></b-td>
<b-td
class="text-right"
data-label="Pricing"
:title="driver.pricingDriver"><span>{{ driver.pricingDriver }}</span></b-td>
</b-tr>
</b-tbody>
<script>
function calculatePricingCustomDriver (event, index) {
let lastValue = this.drivers[index].driverNumerator
if (this.$store.getters.price !== undefined) {
let title = 'Modify numerator'
let message = 'If you modify numerator driver, the calculated pricing will be deleted'
this.$bvModal.msgBoxConfirm(message, {
title: title,
size: 'sm',
buttonSize: 'sm',
okTitle: 'Yes',
okVariant: 'primary',
cancelTitle: 'No',
cancelVariant: 'primary',
hideHeaderClose: false,
centered: true
})
.then(confirmed => {
if (confirmed) {
this.$http.get('delete-price', { params: { id: this.$store.getters.id } })
.then((response) => {
if (response.status === this.$constants.RESPONSE_STATUS_OK) {
this.price = ''
let newNumerator = event.target.value
this.drivers[index].driverNumerator = Number(newNumerator)
let sumTotal = _.sumBy(this.drivers, 'driverNumerator')
for (let i = 0; i < this.drivers.length; i++) {
this.drivers[i].pricingDriver = (this.drivers[i].driverNumerator / sumTotal).toFixed(2)
}
} else {
this.drivers[index].driverNumerator = lastValue
// this is that I want change because it doesn't work fine
document.getElementById('numeratorDriver_' + index).value = lastValue
}
})
} else {
this.drivers[index].driverNumerator = lastValue
document.getElementById('numeratorDriver_' + index).value = lastValue
}
})
.catch(() => {
/* Reset the value in case of an error */
this.$utils.showModalError()
})
} else {
let newNumerator = event.target.value
this.drivers[index].driverNumerator = Number(newNumerator)
let sumTotal = _.sumBy(this.drivers, 'driverNumerator')
for (let i = 0; i < this.drivers.length; i++) {
this.drivers[i].pricingDriver = (this.drivers[i].driverNumerator / sumTotal).toFixed(2)
}
}
}
</script>
how is calculatePricingCustomDriver being loaded into your Vue component? For it to be called like that from #blur you would need to define it as a method:
<template>
<!-- your table-->
</template>
<script>
export default {
name: "MyComponent",
methods : {
calculatePricingCustomDriver () {
// your code
}
}
}
</script>
Or it could be installed as a global mixin

Vue.js - Element UI - get the state of form validation

Steps to reproduce
The recurrence link is this: https://stackblitz.com/edit/typescript-vuejs-element-3kko7a
password input 2
username input 11
Change username to 2// should be able to submit, but not
Expected: formvalid = true
Validate Code here:
checkForm() {
// console.log('validate runs');
// #ts-ignore
const fields = this.$refs.ruleForm.fields;
if (fields.find((f) => f.validateState === 'validating')) {
setTimeout(() => {
this.checkForm();
}, 100);
}
this.formValid = fields.reduce((acc, f) => {
const valid = (f.isRequired && f.validateState === 'success');
const notErroring = (!f.isRequired && f.validateState !== 'error');
return acc && (valid || notErroring);
}, true);
console.log('valid:', this.$data.formValid);
}
Basically you watch ruleForm - so everytime ruleForm changes you trigger checkform - but your validtor triggers on blur after you set ruleForm so you first test then turn valid. change this into a getter:
get formValid(){
const fields = this.$refs.ruleForm.fields || [];
if (fields.find((f) => f.validateState === 'validating')) {
setTimeout(() => {
this.checkForm();
}, 100);
}
return fields.reduce((acc, f) => {
const valid = (f.isRequired && f.validateState === 'success');
const notErroring = (!f.isRequired && f.validateState !== 'error');
return acc && (valid || notErroring);
}, fields.length > 0);
}

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