React does not update state through its function setState when is called with event.target - arrays

Given this code, I want to update selectedOption value by selecting an option.
on Change it will return correct value as event.target, but not in useState.
let options = [
{
value: "",
label: "All",
},
{
value: "0",
label: "With Producers",
},
{
value: "1",
label: "In our warehouse",
},
];
<Form.Control
as="select"
onChange={(e) => {
console.log("e.target.value ==> in select", e.target.value);
setSelectedOption(e.target.value);
handleSubmit(e);
}}
className="form-select"
>
{options.map((option) => {
return (
<option key={option.value} value={option.label}> {option.label} </option>
);
})}
</Form.Control>
const [selectedOption, setSelectedOption] = useState('');
const [filteredData, setFilteredData] = useState([]);
const handleSubmit = (e) => {
console.log('e.target.value', e.target.value)
setSelectedOption(e.target.value);
const data = dataAuction;
let filteredArray = [];
if ( selectedOption == 'With Producers' ) {
filteredArray = data.filter(item => {
// console.log('condition', item.is_resell == '1' && item.is_no_deposit == '1' || item.is_resell == '0')
console.log('is_resell', item.auction.is_resell)
// return item.auction.is_resell == selectedOption;
return item.auction.is_resell == 1 && item.auction.is_no_deposit == 1
});
// setFilteredData(filteredArray);
// setDataAuction(filteredArray)
console.log('if 1');
} else if ( selectedOption == 'In our warehouse' ) {
filteredArray = data.filter(item => {
// console.log('condition', item.is_resell == '1' && item.is_no_deposit == '1' || item.is_resell == '0')
console.log('is_resell', item.auction.is_resell)
// return item.auction.is_resell == selectedOption;
return item.auction.is_resell == 1 && item.auction.is_no_deposit == 0
});
// setFilteredData(filteredArray);
// setDataAuction(filteredArray)
console.log('else if 1');
} else if ( selectedOption == 'All' ) {
console.log('else');
filteredArray = data.map(item => {
// console.log('condition', item.is_resell == '1' && item.is_no_deposit == '1' || item.is_resell == '0')
console.log('else if 2')
// return item.auction.is_resell == selectedOption;
return item
});
// setDataAuction(filteredArray)
}
setFilteredData(filteredArray);
setDataAuction(filteredArray)
console.log('selectedOption =====>', selectedOption)
};
I expect to update selectedOption state. but instead if i click of select, the event.target is correct but it iterates over 'options' array, not in sync with the click event.

Related

How to combine useState hook with switch cases in react

Here is component with the array of items, counters val and spiceValue and rendering block with adding some quantity of spices for example. Every spice has own price, adding or removing by click on plus or minus. How to implement this logic according to best practices of react?
export const SpiceBlock = ({ isCalculated }) => {
const [spiceQuantity, setSpiceQuantity] = useState(0);
var val = 0;
var spiceValue = 0;
Calling useEffect with passed val as argument in any part of this code could not to read val
useEffect((val) => {
setSpiceQuantity();
}, []);
const spicesCount = (event) => {
const direction = event.target.dataset.direction;
const dataSpice = event.target.dataset.spice;
switch (dataSpice) {
case "guarana":spiceValue = 21;break;
case "zhen":spiceValue = 11;break;
case "cinnamon":spiceValue = 33;break;
case "tapioka":spiceValue = 41;break;
default:return false;
}
if (direction === "plus") {
val += spiceValue;
} else if (val - spiceValue > 0) {
val -= spiceValue;
}
};
const spicesArr = [
{ name: "Guarana", data: "guarana" },{ name: "Zhenshen", data: "zhen" },
{ name: "Cinnamon", data: "cinnamon" },{ name: "Tapioka", data: "tapioka" },
];
return (
<div className={`spiceItems ${isCalculated ? "calculated" : ""}`}>
{isCalculated && spicesArr
? spicesArr.map((spice, index) => (
<div className="counter" key={`spice${index}`}>
<button
className="counter__btn"
data-direction="minus"
data-spice={spice.data}
onClick={spicesCount}
>
-
</button>
<label htmlFor="spice" type="text">
{spice.name}
<input
type="text"
name="spice"
value={val}
disabled
className="counter__value"
/>
{spiceQuantity}
</label>
<button
className="counter__btn"
data-direction="plus"
data-spice={spice.data}
onClick={spicesCount}
>
+
</button>
</div>
))
: null}
</div>
);
};
Set val as a state and add it as a dependency to your useEffect. So that every time you set the value of val the setSpiceQuantity function will be triggered
const [val, setVal] = useState(0);
useEffect(() => {
setSpiceQuantity();
}, [val]);
if (direction === "plus") {
setVal(val += spiceValue)
} else if (val - spiceValue > 0) {
setVal(val -= spiceValue)
}
Any variable that is not a state will disappear after rerender, it's better to store variables in the state
const [value, setValue] = useState()
const getValue = type => {
switch (dataSpice) {
case "guarana": return 21;
case "zhen": return 11;
case "cinnamon": return 33;
case "tapioka": return 41;
}
}
const spicesCount = (event) => {
const direction = event.target.dataset.direction;
const dataSpice = event.target.dataset.spice;
const val = getValue(dataSpice);
if (direction === "plus") {
setValue(value => value + spiceValue)
} else if (val - spiceValue > 0) {
setValue(value => value - spiceValue)
}
};
<input
type="text"
name="spice"
value={value}
disabled
className="counter__value"
/>

Type error in react when accessing data from an object array

I am trying to access the resolution timestamp variable from regressions_test_summary however I am getting a type error saying cannot read property of 'resolution_map' undefined.
Variable I am trying to access:
Code from function:
export const getRegressionTestStatus = summary => {
if(summary.regression_test_summary.resolution_timestamp === null) return 'Unresolved'
else if(summary.unit_test_fails || summary.unit_test_errors) return 'Failed'
else if(!summary.unit_test_fails && !summary.unit_test_errors) return 'Success'
console.log('from summary', summary);
}
export const getLogIcon = (unitTest, size) => {
if(unitTest.result && typeof(unitTest.result[0]) === 'string') {
return <ErrorIcon className={`LogIcon${size} TestError`} />
}
else {
return <FiberManualRecordIcon
className={`LogIcon${size} ${!unitTest.result ? 'TestNA' : unitTest.result[0] ? 'TestPass' : 'TestFail'}`}
/>
}
}
regressiontestData:
const getIcon = (summary) => {
const status = getRegressionTestStatus(summary)
if(status === 'Unresolved') return <ScheduleIcon style={{color: 'var(--update-bg-color)'}} />
else if(status === 'Failed') return <CloseIcon style={{color: 'var(--reject-fg-color)'}} />
else if(status === 'Success') return <CheckIcon style={{color: 'var(--approve-bg-color)'}} />
console.log('summary', summary);
}
useEffect(() => {
async function onLoadRegressionTests() {
loading.setLoading(true)
const results = await verifiedGet(`get_regression_tests/${(currentPage - 1) * resPerPage}/${resPerPage}`, user.user)
if(results.status === 0) {
setRegressionTestsData(results.data)
setPageNumbers(getPageNumbersList(results.total_count, resPerPage))
} else if(results.status >=20 && results.status <=30) {
snackbar.statusCheck(results)
user.setSessionTokenMatches(false)
} else snackbar.statusCheck(results)
loading.setLoading(false)
}
if(user.f_auth([1, 20])) onLoadRegressionTests()
else setRegressionTestsData('You do not have the authority to view this page.')
}, [currentPage])
const onRegressionTestClick = (id) => props.history.push(`test?id=${id}`)
const onRequestRegressionTestClick = () => props.history.push('/requesttest')
const onPageNumberClick = (pageNum) => {
setCurrentPage(pageNum)
}
I can see the summary is an array. You can not access properties of an element of arrays like this.
When you get the summary, try this:
const getIcon = summary.data.map((item) => {
const status = getRegressionTestStatus(item)
if(status === 'Unresolved') return <ScheduleIcon style={{color: 'var(--update-bg-color)'}} />
else if(status === 'Failed') return <CloseIcon style={{color: 'var(--reject-fg-color)'}} />
else if(status === 'Success') return <CheckIcon style={{color: 'var(--approve-bg-color)'}} />
)}
This will return a new array of Icon you want.

React useState not updating the states on submit form

const [user, setuser] = useState({
fName: '', lName: '', password: '', email: '', username: ''
})
const [fNameError, setfNameError] = useState('');
const [lNameError, setlNameError] = useState('');
const [emailError, setemailError] = useState('');
const [passwordError, setpasswordError] = useState('');
const [usernameError, setusernameError] = useState('');
const changeHandler = (e) => {
setuser({
...user, [e.currentTarget.name]: e.currentTarget.value
})
}
const inputChecker = () => {
user.fName === '' || user.fName.length < 3 ? setfNameError('invalid') : setfNameError('valid');
user.lName === '' || user.lName.length < 3 ? setlNameError('invalid') : setlNameError('valid');
user.username === '' || user.username.length < 5 ? setusernameError('invalid') : setusernameError('valid');
user.password === '' || user.password.length < 6 ? setpasswordError('invalid') : setpasswordError('valid');
validateEmail(user.email) ? setemailError('valid') : setemailError('invalid');
if (fNameError == 'valid' && lNameError == 'valid' && emailError == 'valid' && passwordError == 'valid' && usernameError == 'valid') {
if (fNameError == 'valid') {
return true
}
return false
}
const submitHandler = (e) => {
e.preventDefault();
//
On submitting the form and calling the submitHandler if all errors
in the inputChecker function are valid I need inputChecker to return
true but it returns false on first click even when all are valid but
when i click it for the second time it return true and below check works
// Can someone tell me what I am doing wrong
if (inputChecker()) {
console.log(user);
}
}
Set state is async operation. You are setting the state and then checking its value which will always return you the old one. Thats the reason it returns true in the second time.
Refactor your code as below, and check again.
const inputChecker = () => {
let isFNameValid = true;
let isLNameValid = true;
let isUsernameValid = true;
let isPasswordValid = true;
let isEmailValid = true;
if(user.fName === '' || user.fName.length < 3) {
setfNameError('invalid');
isFNameValid = false;
}
else {
setfNameError('valid');
isFNameValid = true;
}
if(user.lName === '' || user.lName.length < 3) {
setlNameError('invalid');
isLNameValid = false;
}
else {
setlNameError('valid');
isLNameValid = true;
}
if(user.username === '' || user.username.length < 5) {
setusernameError('invalid');
isUsernameValid = false;
}
else {
setusernameError('valid');
isUsernameValid = true;
}
if(user.password === '' || user.password.length < 6) {
setpasswordError('invalid');
isPasswordValid = false;
}
else {
setpasswordError('valid');
isPasswordValid = true;
}
if(validateEmail(user.email)) {
setemailError('valid');
isEmailValid = true;
}
else {
setemailError('invalid');
isEmailValid = false;
}
if (isFNameValid && isLNameValid && isUsernameValid && isPasswordValid && isEmailValid) {
return true;
} else
return false;
}

How to adjust valid input check method for SpinButton?

I'm using Office UI Fabric and have a SpinButton implemented. There is some kind of automatic validation that prevents me from using anything apart from numbers as an input. The problem is, I cannot even use the subtract sign.
How can I change that?
I tried implementing my own onValidate() method, to cancel out the default one, and even though it's called, it doesn't stop the SpinButton input from being deleted when different from numbers
onValidate={() => console.log('Validate meeee')}
The whole SpinButton looks like this (it's mixed with JS):
static getNumericBox(formField: EntityFormField, onChange: EntityFormControlOnChangeType): JSX.Element {
let rangeFrom: number = -999999;
let rangeTo: number = 999999;
const controlParams = EntityFormHelpers.getNumericControlParams(formField.controlType);
if (controlParams) {
rangeFrom = controlParams.rangeFrom;
rangeTo = controlParams.rangeTo;
}
return (
<React.Fragment key={formField.fieldName}>
<SpinButton
key={formField.fieldName}
className={'NumericBox ' + this.getValidationClassName(formField)}
label={formField.displayName}
labelPosition={Position.top}
componentRef={(component: any) => {
if (component) {
const inputElement = component._input.current;
const labelElement = inputElement.parentElement.previousSibling.firstChild;
if (formField.validation.isRequired && !formField.displayOnly) {
labelElement.setAttribute('required', '');
}
inputElement.value = formField.value;
inputElement.onkeydown = (event: any) => {
if (event.target.value.toString().length > rangeTo.toString().length + 1 && event.target.value.toString().length > rangeFrom.toString().length + 1) {
event.preventDefault();
event.stopPropagation();
}
};
inputElement.onkeyup = (event: any) => {
let numberValue = Number(event.target.value);
if (!numberValue) {
numberValue = formField.validation.isRequired ? Number(0) : null;
}
onChange(formField.fieldName, numberValue);
};
}
}}
onValidate={() => console.log('Validate meeee')}
onIncrement={(value: string) => {
if (Number(value) + 1 > rangeTo) {
formField.value = value;
} else {
value = String(+value + 1);
onChange(formField.fieldName, value);
formField.value = value;
}
}}
onDecrement={(value: string) => {
if (Number(value) - 1 < rangeFrom) {
formField.value = value;
} else {
value = String(+value - 1);
onChange(formField.fieldName, value);
formField.value = value;
}
}}
value={formField.value}
min={rangeFrom}
max={rangeTo}
step={1}
onBlur={(event: any) => {
const numberValue = Number(event.target.value);
if (numberValue) {
if (numberValue < rangeFrom) {
onChange(formField.fieldName, rangeFrom);
}
else if (numberValue > rangeTo) {
onChange(formField.fieldName, rangeTo);
}
}
}}
disabled={formField.displayOnly}
/>
{this.getDescriptionControl(formField)}
</React.Fragment>);
}
Problem is in the onkeyup methods. Everything kept overwriting as soon as a single key was pressed. A bit of fiddling around fixed the whole thing.
In case anyone is interested, here's the final and working state:
static getNumericBox(formField: EntityFormField, onChange: EntityFormControlOnChangeType): JSX.Element {
let rangeFrom: number = -999999;
let rangeTo: number = 999999;
const controlParams = EntityFormHelpers.getNumericControlParams(formField.controlType);
if (controlParams) {
rangeFrom = controlParams.rangeFrom;
rangeTo = controlParams.rangeTo;
}
return (
<React.Fragment key={formField.fieldName}>
<SpinButton
key={formField.fieldName}
className={'NumericBox ' + this.getValidationClassName(formField)}
label={formField.displayName}
labelPosition={Position.top}
componentRef={(component: any) => {
if (component) {
const inputElement = component._input.current;
const labelElement = inputElement.parentElement.previousSibling.firstChild;
if (formField.validation.isRequired && !formField.displayOnly) {
labelElement.setAttribute('required', '');
}
inputElement.value = formField.value;
inputElement.onkeydown = (event: any) => {
if (event.target.value.toString().length > rangeTo.toString().length + 1 && event.target.value.toString().length > rangeFrom.toString().length + 1) {
event.preventDefault();
event.stopPropagation();
}
};
inputElement.onkeyup = (event: any) => {
const isValidKeyCode =
event.which === KeyCodes.up ||
event.which === KeyCodes.down ||
event.which === KeyCodes.left ||
event.which === KeyCodes.right ||
event.which === KeyCodes.backspace ||
event.which === KeyCodes.del ||
event.which === KeyCodes.a && event.ctrlKey ||
event.which === KeyCodes.x && event.ctrlKey ||
event.which === KeyCodes.c && event.ctrlKey ||
event.which === KeyCodes.v && event.ctrlKey ||
event.which === KeyCodes.subtract ||
event.which === KeyCodes.dash;
const isValidNumberKeyCode = (
(event.which >= KeyCodes.zero && event.which <= KeyCodes.nine) ||
(event.which >= KeyCodes.zero_numpad && event.which <= KeyCodes.nine_numpad)
);
if (!isValidKeyCode && !isValidNumberKeyCode) {
onChange(formField.fieldName, null);
} else if (event.target.value === "-") {
return;
} else {
let numberValue = parseInt(event.target.value);
if (!numberValue && numberValue !== 0) {
numberValue = formField.validation.isRequired ? +"0" : null;
}
onChange(formField.fieldName, numberValue);
}
};
}
}}
onIncrement={(value: string) => {
if (Number(value) + 1 > rangeTo) {
formField.value = value;
} else {
value = String(+value + 1);
onChange(formField.fieldName, value);
formField.value = value;
}
}}
onDecrement={(value: string) => {
if (Number(value) - 1 < rangeFrom) {
formField.value = value;
} else {
value = String(+value - 1);
onChange(formField.fieldName, value);
formField.value = value;
}
}}
value={formField.value}
min={rangeFrom}
max={rangeTo}
step={1}
onBlur={(event: any) => {
const numberValue = Number(event.target.value);
if (numberValue) {
if (numberValue < rangeFrom) {
onChange(formField.fieldName, rangeFrom);
}
else if (numberValue > rangeTo) {
onChange(formField.fieldName, rangeTo);
}
}
}}
disabled={formField.displayOnly}
/>
{this.getDescriptionControl(formField)}
</React.Fragment>);
}

redux form not updating select field

I am using version 7.2.x and i have fixed the bug with onBlur where it resets teh value of the input. Problem i have now is i can see the state changes and it holds the correct value now but on the gui it does not change the value to show the correct one.
In my reducer i have forms: formReducer,.
in my component class
const mapStateToProps = state => {
return state;
}
function mapDispatchToProps(dispatch) {
return bindActionCreators(
{
change,
},
dispatch
);
}
const IAMSubnetFormP = reduxForm({
form: 'iamSubnetNewForm', // a unique name for this form
fields: ['type_of_subnet_id', 'subnet_type', 'location', 'security_zone', 'seczone', 'routing_domain', 'zone_confirm', 'subnet_size', 'subnet_confirm', 'iam_addressing_type_id', 'address_space', 'allocation_range', 'new_subnet', 'desc_vr', 'desc_vr_confirm', 'l2env', 'l2env_confirm', 'l3dev', 'l3dev_confirm', 'zone_platform', 'wo', 'iam_network_diagram_id', 'subnet_class', 'project', 'justification', 'project_confirm']
})(IAMSubnetForm);
export default connect(mapStateToProps, mapDispatchToProps)(IAMSubnetFormP);
the select box is rendered as follows
renderTypeOfSubnet() {
let disabled = true;
let data = this.state.data;
console.log(this)
if (Object.keys(this.props.forms.iamSubnetNewForm).length > 0
&& 'values' in this.props.forms.iamSubnetNewForm
&& 'type_of_subnet_id' in this.props.forms.iamSubnetNewForm.values) {
disabled = false;
}
return <Field
label="Please select the type of subnet?"
name="type_of_subnet_id"
component={this.renderSelectField}
type="select" disabled={disabled} data={data}
onBlur={() => {}}
/>;
}
renderSelectField(field) {
const { input, label, type, meta: { touched, error, warning }, data, disabled } = field;
let options = [];
const className = `form-group ${touched && error ? 'has-danger' : ''}`;
const uniqueList = [];
const uniqueListObject = [];
if (input.name == 'type_of_subnet_id') {
this.state.data.map(row => {
if (uniqueList.indexOf(row.subnet_type) === -1) {
uniqueList.push(row.subnet_type);
uniqueListObject.push({ id: row.iam_type_id, text: row.subnet_type, vlan: row.vlan });
}
});
let newuniqueListObject = uniqueListObject.sort(function(a, b) {
var nameA = a.text.toLowerCase(),
nameB = b.text.toLowerCase();
if (nameA < nameB)
//sort string ascending
return -1;
if (nameA > nameB) return 1;
return 0; //default return value (no sorting)
});
options = this.populateOptionsObject(newuniqueListObject);
}
let id = 'select_' + input.name;
if (input.name == 'security_zone' && this.props.forms.iamSubnetNewForm.values.location != '') {
if (this.props.forms.iamSubnetNewForm.values.subnet_type != 'NAT') {
options.unshift(
<option key="" value="">
-- select --
</option>
);
} else {
uniqueListObject.push({ id: 'E1', text: 'N/A' });
options = this.populateOptionsObject(uniqueListObject);
}
} else if (input.name != 'wo' && input.name != 'iam_network_diagram_id' && input.name != 'subnet_class') {
if (this.props.forms.iamSubnetNewForm.values.subnet_type != 'NAT') {
options.unshift(
<option key="" value="">
-- select --
</option>
);
} else if (input.name == 'zone_platform' && this.props.forms.iamSubnetNewForm.values.l3dev_confirm == 'Yes' && this.props.forms.iamSubnetNewForm.values.subnet_type == 'NAT') {
options.unshift(
<option key="N/A" value="N/A">
N/A
</option>
);
} else {
options.unshift(
<option key="" value="">
-- select --
</option>
);
}
} else if (input.name == 'subnet_class' && this.props.forms.iamSubnetNewForm.values.l3dev_confirm == 'Yes' && this.props.forms.iamSubnetNewForm.values.iam_network_diagram_id != '' && this.props.forms.iamSubnetNewForm.values.subnet_type == 'NAT') {
options.unshift(
<option key="N/A" value="N/A">
N/A
</option>
);
}
return (
<div className={className}>
<label className="control-label col-sm-4">{label}</label>
<div className="col-sm-8">
<select
{...input}
onBlur={() => {}}
className="form-control form-control-inline"
type={type}
onChange={event => {
this.resetValues(event);
if (event.target.name == 'type_of_subnet_id') {
if (event.target.value.length > 0) {
let type_of_subnet = _.find(uniqueListObject, { id: event.target.value });
if (type_of_subnet.text == 'NAT') {
this.props.change('security_zone', 'N/A');
this.props.change('seczone', 'E1');
}
this.props.change('subnet_type', type_of_subnet.text);
this.props.change('vlan', type_of_subnet.vlan);
} else {
this.props.change('subnet_type', '');
this.props.change('seczone', '');
this.props.change('security_zone', '');
}
}
this.props.change(event.target.name, event.target.value);
}}
disabled={disabled}
>
{options}
</select>
</div>
<div className="row-fluid">
<div className="col-sm-2" />
<div className="col-sm-10">
{touched &&
((error && (
<span className="text-danger">
<i className="fa fa-exclamation-circle" aria-hidden="true" /> {error}
</span>
)) ||
(warning && (
<span className="text-warning">
<i className="fa fa-question-circle" aria-hidden="true" /> {warning}
</span>
)))}
</div>
</div>
</div>
);
}
It seems like after the change event a re-render is not triggered to update the value on the from end. however it holds the correct value in props
I have replicated issue here
https://codesandbox.io/s/24x376j98n
i need to be able to support multiple forms. for example forms in different components but being rendered on the same view
You should pass value prop to "select" tag
<select
...
value={event.target.value}
...
/>
</select>
Check this return statement
return (
<div className={className}>
<label className="control-label col-sm-4">{label}</label>
<div className="col-sm-8">
<select
{...input}
onBlur={() => {
console.log(field);
console.log(input.value);
}}
className="form-control form-control-inline"
type={type}
value={event.target.value}
onChange={event => {
this.resetValues(event);
if (event.target.name == "type_of_subnet_id") {
if (event.target.value.length > 0) {
let type_of_subnet = _.find(uniqueListObject, {
id: event.target.value
});
if (type_of_subnet.text == "NAT") {
this.props.change("security_zone", "N/A");
this.props.change("seczone", "E1");
}
this.props.change("subnet_type", type_of_subnet.text);
this.props.change("vlan", type_of_subnet.vlan);
} else {
this.props.change("subnet_type", "");
this.props.change("seczone", "");
this.props.change("security_zone", "");
}
} else if (
event.target.name == "routing_domain" &&
this.props.forms.iamSubnetNewForm.values.subnet_type == "NAT" &&
this.props.forms.iamSubnetNewForm.values.seczone == "E1"
) {
this.props.change("zone_confirm", "Yes");
} else if (
event.target.name == "security_zone" &&
this.props.forms.iamSubnetNewForm.values.subnet_type != "NAT" &&
event.target.value.length > 0
) {
let type_of_subnet = _.find(uniqueListObject, {
id: event.target.value
});
this.props.change("seczone", type_of_subnet.seczone);
} else if (event.target.name == "subnet_size") {
if (event.target.value != "") {
this.props.change(
"iam_addressing_type_id",
data[0].iam_addressing_type_id
);
let self = this;
this.props
.requestSubnet(
data[0].iam_addressing_type_id,
this.props.forms.iamSubnetNewForm.values.location,
event.target.value,
this.props.forms.iamSubnetNewForm.values
.type_of_subnet_id,
this.props.forms.iamSubnetNewForm.values.security_zone,
this.props.forms.iamSubnetNewForm.values.routing_domain
)
.then(response => {
let data = response.payload.data;
if (data.header.error) {
if (
data.header.message ==
"Unable to assign a new subnet. The IP Administrator has been notified."
) {
self.setState({
request_subnet: data.header.message
});
} else {
self.handleShowError({
show: true,
errorMsg: data.header.message
});
}
} else {
this.props.change(
"address_space",
data.body.recordset.record.address_space
);
this.props.change(
"allocation_range",
data.body.recordset.record.allocation_range
);
this.props.change(
"new_subnet",
data.body.recordset.record.new_subnet
);
self.setState({ request_subnet: "" });
}
});
} else {
this.props.change(
"iam_addressing_type_id",
data[0].iam_addressing_type_id
);
}
} else if (event.target.name == "zone_platform") {
if (
this.props.forms.iamSubnetNewForm.values.subnet_type !=
"NAT" &&
(this.props.forms.iamSubnetNewForm.values.l3dev_confirm !=
"" &&
this.props.forms.iamSubnetNewForm.values.l3dev_confirm !=
"No")
) {
this.props.fetchIAMInc().then(response => {
let data = response.payload.data.body.recordset.record;
data.map(row => {
if (uniqueList.indexOf(row.remedy_inc) === -1) {
uniqueList.push(row.remedy_inc);
uniqueListObject.push({
id: row.remedy_inc,
text: row.remedy_inc
});
}
});
let newuniqueListObject = uniqueListObject.sort(function (
a,
b
) {
var nameA = a.text.toLowerCase(),
nameB = b.text.toLowerCase();
if (nameA < nameB)
//sort string ascending
return -1;
if (nameA > nameB) return 1;
return 0; //default return value (no sorting)
});
let options = this.populateOptionsObject(
newuniqueListObject
);
options.unshift(
<option key="" value="">
-- select --
</option>
);
this.setState({ wo: options });
});
}
} else if (event.target.name == "wo") {
if (
this.props.forms.iamSubnetNewForm.values.subnet_type !=
"NAT" &&
event.target.value != ""
) {
this.props
.fetchNetworkTopology(event.target.value)
.then(response => {
let data = response.payload.data.body.recordset.record;
data.map(row => {
if (uniqueList.indexOf(row.id) === -1) {
uniqueList.push(row.id);
const text = `${row.remedy_inc} v${row.version}`;
uniqueListObject.push({ id: row.id, text: text });
}
});
let newuniqueListObject = uniqueListObject.sort(function (
a,
b
) {
var nameA = a.text.toLowerCase(),
nameB = b.text.toLowerCase();
if (nameA < nameB)
//sort string ascending
return -1;
if (nameA > nameB) return 1;
return 0; //default return value (no sorting)
});
let options = this.populateOptionsObject(
newuniqueListObject
);
options.unshift(
<option key="" value="">
-- select --
</option>
);
this.setState({ networkTopology: options });
});
} else if (
this.props.forms.iamSubnetNewForm.values.subnet_type ==
"NAT" &&
(this.props.forms.iamSubnetNewForm.values.l2env_confirm !=
"" &&
this.props.forms.iamSubnetNewForm.values.l2env_confirm !=
"No")
) {
this.props
.fetchNetworkTopology(event.target.value)
.then(response => {
let data = response.payload.data.body.recordset.record;
data.map(row => {
if (uniqueList.indexOf(row.id) === -1) {
uniqueList.push(row.id);
const text = `${row.remedy_inc} v${row.version}`;
uniqueListObject.push({ id: row.id, text: text });
}
});
let newuniqueListObject = uniqueListObject.sort(function (
a,
b
) {
var nameA = a.text.toLowerCase(),
nameB = b.text.toLowerCase();
if (nameA < nameB)
//sort string ascending
return -1;
if (nameA > nameB) return 1;
return 0; //default return value (no sorting)
});
let options = this.populateOptionsObject(
newuniqueListObject
);
options.unshift(
<option key="" value="">
-- select --
</option>
);
this.setState({ networkTopology: options });
});
}
} else if (event.target.name == "iam_network_diagram_id") {
if (
this.props.forms.iamSubnetNewForm.values.subnet_type !=
"NAT" &&
event.target.value != ""
) {
this.props.fetchSubnetClass().then(response => {
let data = response.payload.data.body.recordset.record;
data.map(row => {
if (uniqueList.indexOf(row.descriptor) === -1) {
uniqueList.push(row.descriptor);
const text = `${row.name}`;
uniqueListObject.push({
id: row.descriptor,
text: text
});
}
});
let newuniqueListObject = uniqueListObject.sort(function (
a,
b
) {
var nameA = a.text.toLowerCase(),
nameB = b.text.toLowerCase();
if (nameA < nameB)
//sort string ascending
return -1;
if (nameA > nameB) return 1;
return 0; //default return value (no sorting)
});
let options = this.populateOptionsObject(
newuniqueListObject
);
options.unshift(
<option key="" value="">
-- select --
</option>
);
this.setState({ subnetClass: options });
});
} else if (
this.props.forms.iamSubnetNewForm.values.subnet_type ==
"NAT" &&
event.target.value != ""
) {
let data = _.filter(this.state.data, {
iam_type_id: this.props.forms.iamSubnetNewForm.values
.type_of_subnet_id
});
data = _.filter(data, {
loczone: this.props.forms.iamSubnetNewForm.values.location
});
data = _.filter(data, {
seczone: this.props.forms.iamSubnetNewForm.values.seczone
});
data = _.filter(data, {
netzone: this.props.forms.iamSubnetNewForm.values
.routing_domain
});
let found = _.find(data, {
subnet_size: this.props.forms.iamSubnetNewForm.values
.subnet_size
});
if (found === undefined) {
} else {
this.props.change("subnet_class", "N/A");
this.props.change("project", "N/A");
this.props.change("justification", "N/A");
this.props.change("project_confirm", "Yes");
this.setState({ buttonDisabled: false });
}
}
} else if (event.target.name == "subnet_class") {
if (
this.props.forms.iamSubnetNewForm.values.subnet_type !=
"NAT" &&
event.target.value != ""
) {
let data = _.filter(this.state.data, {
iam_type_id: this.props.forms.iamSubnetNewForm.values
.type_of_subnet_id
});
data = _.filter(data, {
loczone: this.props.forms.iamSubnetNewForm.values.location
});
data = _.filter(data, {
seczone: this.props.forms.iamSubnetNewForm.values.seczone
});
data = _.filter(data, {
netzone: this.props.forms.iamSubnetNewForm.values
.routing_domain
});
let found = _.find(data, {
subnet_size: this.props.forms.iamSubnetNewForm.values
.subnet_size
});
if (event.target.value == "Shared" && found !== undefined) {
this.props.change("project", "N/A");
this.props.change("justification", "N/A");
this.props.change("project_confirm", "Yes");
this.setState({ buttonDisabled: false });
} else if (
event.target.value != "Shared" ||
found == undefined
) {
this.setState({ buttonDisabled: true });
}
}
}
this.props.change(event.target.name, event.target.value);
input.onChange(event);
this.setState(prevState => ({
rerender: !prevState.rerender
}));
console.log("need to rerender");
}}
disabled={disabled}
>
{options}
</select>
</div>
<div className="row-fluid">
<div className="col-sm-2" />
<div className="col-sm-10">
{touched &&
((error && (
<span className="text-danger">
<i className="fa fa-exclamation-circle" aria-hidden="true" />{" "}
{error}
</span>
)) ||
(warning && (
<span className="text-warning">
<i className="fa fa-question-circle" aria-hidden="true" />{" "}
{warning}
</span>
)))}
</div>
</div>
</div>
);

Resources