Jeffrey Delos Santos
Jeffrey Delos Santos

Reputation: 77

Trigger an onChange event after a select element is re-rendered in React

enter image description here

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

  }

Upvotes: 1

Views: 1538

Answers (2)

Jeffrey Delos Santos
Jeffrey Delos Santos

Reputation: 77

I just have to call the onChange functions on the fetching data inside the setState execution and pass a callback function that changes the state to default(0)

handleChange function:

handleChangeSelect = (e, callback = function () { }) => {
    if (e.target) {
      this.setState({
        [e.target.id]: e.target.value
      }, callback());
    } else {
      this.setState(e, callback());
    }
  };

data fetching function

   /**
    * 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 }, this.onChangeCity({ selectCity: 0 }));
    } 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 }, this.onChangeBarangay({ selectBarangay: 0 }));

    } else {
      retryRequest(this.getAllBarangay);
    }

  }

Upvotes: 0

buzatto
buzatto

Reputation: 10382

you can use componentDidUpdate or pass a callback function to setState like you did. But your callback is only returning the inner function, not invoking it. it should be like:

  onChangeProvince = (e) => {
    // removed '{ return }' because there's no need on 1 liner
    this.handleChangeSelect(e, () => this.getAllCity());
  }

  onChangeCity = (e) => {
    this.handleChangeSelect(e, () => this.getAllBarangay());
  }

Upvotes: 1

Related Questions