score:6

Accepted answer

I see two options:

Option 1

You can prevent the rendering of your Select component until the request is finished. This will mean your constructor will fire after you have the data and will be initialized correctly.

render() {
  if (this.state.defaultValue) {
    return (
      <Select 
        options={this.state.values} 
        defaultValue={this.state.defaultValue} 
      />
    )
  } else {
    return null; // or loading graphic
  }
}

Option 2

In your Select component, use a lifecycle method like componentDidUpdate to check if the defaultValue prop has changed from the last render. If so, set the default value in state. This will make it so that defaultValue only gets set once.

componentDidUpdate(prevProps) {
  if (this.props.defaultValue !== prevProps.defaultValue) {
    this.setState({ defaultValue: this.props.defaultValue });
  }
}

Related Query

More Query from same tag