Reputation: 173
I am trying to do async call to fetch data when dropdown value is not '--'. componentDidMount is not called when select value state updated.
const { Fragment } = React;
export class HierarchySelect extends Component {
constructor (props) {
super(props);
this.state = {
department: '',
sections: [],
section: '--'
};
}
componentDidMount () {
if (this.state.section !== '--') {
console.log('inside check');
axios({
method: 'GET',
url: constants.url,
headers: {
'x-access-token': authService.getAccessToken()
}
}).then((res) => {
if (res.status === 200) {
console.log('hulalala', res);
}
})
.catch((err) => { console.log(err); });
}
}
handleChange (value, type, error) {
switch (type) {
case 'section':
this.setState({
section: value,
class: '--'
});
this.props.getClasses({ department: this.state.department, section: value });
break;
default:
}
}
render () {
return (
<Fragment>
<select id="lang" className="department" onChange={e => this.handleChange(e.target.value, 'department')} value={this.state.department}>
{['--', ...this.props.deptHierarchy.data.map(obj => obj.depId).sort((a, b) => a - b)].map(d => <option key={d} value={d}>{d}</option>)}
</select>
<select id="lang" className="section" onChange={e => this.handleChange(e.target.value, 'section')} value={this.state.section}>
{['--', ...this.state.sections].map(d => <option key={d} value={d}>{d}</option>)}
</select>
</Fragment>
);
}
}
export default HierarchySelect;
How to do async call when we select the particular value from the dropdown or when option value is not '--'.
Upvotes: 0
Views: 733
Reputation: 15290
componentDidMount
is called once in life.So,better to put API call in one helper function and called it from componentDidMount
and onChange event .
doAsyncCall = ()=>{
if (this.state.section !== '--') {
console.log('inside check');
axios({
method: 'GET',
url: constants.url,
headers: {
'x-access-token': authService.getAccessToken()
}
}).then((res) => {
if (res.status === 200) {
console.log('hulalala', res);
}
})
.catch((err) => { console.log(err); });
}
}
componentDidMount () {
this.doAsyncCall();
}
handleChange
handleChange = (value, type, error)=>{
this.setState(()=>{
this.doAsyncCall();
return {
section: value,
class: '--'
};
});
//rest code
}
Upvotes: 2