I'm fairly new to React.
I have selector which returns whatever the user selects.
handleChanged(e){
const { onSelectcountry } = this.props;
onSelectcountry(e.target.value)
}
return (
<div>
<Input type="select" name="select" value={Country} onChange={this.handleChanged.bind(this)}>
{
country.map((item) => {
return (<option value={item._id} key={item._id}> {item.name}</option>);
})
}
</Input>
</div>
);
i dispatch action depend on user select,
import { fetchNews} from '../../actions';
getNews(filterNews) {
const { fetchNews } = this.props;
fetchNews(filterNews);
}
onSelectcountry(country) {
this.setState({ Country: country});
this.getNews({
this.state,
})
}
<CountrySelector onSelectcountry={this.onSelectcountry.bind(this)} Country={Country}/>
The problem is: When the selected value changes, it shows the value of the previous selection.
this is due to the asynchronous nature of setState
You have some options:
onSelectcountry(country) {
this.setState(
{ Country: country},
() => this.getNews({ this.state })
);
}
getNews
with manually composed arguments onSelectcountry(country) {
this.setState({ Country: country });
this.getNews({
...this.state,
Country: country
})
}
getNews
in componentDidUpdate
callback, e.g. leave onSelectcountry simple and care only about Country state updates, and handle real state update in expected manner.
componentDidUpdate(prevProps, prevState){
// coundition may vary depending on your requirements
if (this.state.Country !== prevState.Country) {
this.getNews(this.state);
}
}
onSelectcountry(country) {
this.setState({ Country: country});
}