I have these 3 select elements, and each one of them fetches data from the backend and uses it as their options. If the Province changes, the City fetches data and it should fire an onChange event also so that the Barangay(Town) can fetch its data.
The HTML/JSX template:
<div className="row mb-3">
<div className="col">
<Combobox label="Province" onChange={this.onChangeProvince} className="custom-select mr-1" id="selectProvince" options={createSelectItems(this.state.provinceData)} />
</div>
<div className="col">
<Combobox label="City" onChange={this.onChangeCity} className="custom-select mr-1" id="selectCity" options={createSelectItems(this.state.cityData)} />
</div>
<div className="col">
<Combobox label="Barangay" onChange={this.onChangeBarangay} className="custom-select mr-1" id="selectBarangay" options={createSelectItems(this.state.barangayData)} />
</div>
</div>
Event functions:
handleChangeSelect = (e, callback = function () { }) => {
this.setState({
[e.target.id]: e.target.value
}, callback());
};
onChangeProvince = (e) => {
this.handleChangeSelect(e, () => { return this.getAllCity });
}
onChangeCity = (e) => {
this.handleChangeSelect(e, () => { return this.getAllBarangay });
}
Functions for data fetching:
/**
* get all Province data
*/
async getAllProvince() {
let data = await fetchGet("http://localhost:3000/api/province/get/combobox");
if (data !== false) {
this.setState({ provinceData: data });
} else {
retryRequest(this.getAllProvince);
}
}
/**
* get all City data and append it to the Combobox
*/
async getAllCity() {
let data = await fetchGet(`http://localhost:3000/api/city/get/combobox/byparent/${this.state.selectProvince}`);
if (data !== false) {
this.setState({ cityData: data });
} else {
retryRequest(this.getAllCity);
}
}
/**
* get all Barangay data and append it to the Combobox
*/
async getAllBarangay() {
let data = await fetchGet(`http://localhost:3000/api/barangay/get/combobox/byparent/${this.state.selectCity}`);
if (data !== false) {
this.setState({ barangayData: data });
} else {
retryRequest(this.getAllBarangay);
}
}
question from:
https://stackoverflow.com/questions/65938189/trigger-an-onchange-event-after-a-select-element-is-re-rendered-in-react 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…