I am new to React so this question might be a little dumb. I am trying to get the dropdown values from backend. The problem I'm facing is that the program is not filling the list with the items even after the async-await function returns the items. Any help would be appreciated.
Code for loading data from backend:-
getDataSources = async () => { try { return await axios.post("http://localhost:5000/configure_get_sources", { headers: { "content-type": "application/json" } } ); } catch (e) { console.log(e); } };
For the dropdown, I have the code mentioned below:-
var selectSources = []; this.getDataSources().then((res) => { for (var i = 0; i < res.data.length; i++) { selectSources.push("<option value='" + res.data[i] + "'>" + res.data[i] + "</option>"); }; }); return ( <div className="container"> <div className="row"> <label className="col-md-4" >Data Source: </label> <select className="col-md-7"> { selectSources.map(id => <option key={id} value={id}>{id}</option> ) } </select> </div> </div );
componentDidMountby updating the result into your state withsetStateand use selectSources from this.state.try catchwill not be able to handle API call errors, you need to use the.then()and.catch()methods in the axios promise.