reactjsreduxonselect

react - onselect change display previous value


I'm fairly new to React.

I have selector which returns whatever the user selects.

Code Example:

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.


Solution

  • this is due to the asynchronous nature of setState You have some options:

    1. use setState's optional callback, it will be invoked after updating state.
        onSelectcountry(country) {
            this.setState(
              { Country: country},
              () => this.getNews({ this.state })
            );
        }
    
    1. Call getNews with manually composed arguments
        onSelectcountry(country) {
            this.setState({ Country: country });
            this.getNews({
              ...this.state,
              Country: country
            })
        } 
    
    1. Call 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});
        }