calling externally componentDidMount() in react

I have a requirement in which once page gets loaded my dropdownlist should be populated. for that I put that code in componentDidMount().

  componentDidMount() {
    axios.get(`http://localhost:8080/country_code`).then((res) => {
      const countryData = res.data;
      this.setState({ countryData });
      alert(countryData);
    });
  }

I have one user input field in which person enter the value and save it into database. I want once user save that value into DB, my dropdown should get refresh and that value should be visible in the dropdown. How can I externally call componentDidMount()? is there any better way to handle the same?

As of now list is getting refreshed only when user resfresh the page.


Solution 1:

You can't call externally componentDidMount() method !. so you need set common function which is call in componentDidMount() and onChange dropdown value. see below code !

class App extends Component {
  componentDidMount() {
    this.handleCallApi();
  }

  handleCallApi = () => {
    axios.get(`http://localhost:8080/country_code`).then((res) => {
      const countryData = res.data;
      this.setState({ countryData });
      alert(countryData);
    });
  }

  render() {
    return (
      <div>
        <button onClick={this.handleCallApi}>Call Api</button>
      </div>
    );
  }
}
export default App;

Solution 2:

You can't call componentDidMount externally but you can extract the code in componentDidMount to a method and can call it in both componentDidMount and onSave.

 alertDropDown = () => {
    axios.get(`http://localhost:8080/country_code`).then((res) => {
          const countryData = res.data;
          this.setState({ countryData });
          alert(countryData);
        });
    }

componentDidMount

componentDidMount() {
  this.alertDropDown()
}

On DB save method

onSave = () => {
 this.alertDropDown()
}

Solution 3:

You can't call the componentDidMount(), as it's a lifecycle method and is called at initial render. You can expose a function and call that function from inside the componentDidMount() something like:

updateDropdownData = () => {
 axios.get(`http://localhost:8080/country_code`).then((res) => {
      const countryData = res.data;
      this.setState({ countryData });
      alert(countryData);
    });
}

componentDidMount() {
  this.updateDropdownData()
}

And you can call this.updateDropdownData() from anywhere you want. Just like:

onSomeUserAction = () => {
 this.updateDropdownData()
}