Skip to content

Async loadOptions doesn't get recalled after receiving new props #812

@alexjesp

Description

@alexjesp

Context

I have an API that only gives me more data after the initial render of my React application. Imagine initially in my app component I have this.props.activeItemId as null. Then when the extra data fetches, it rerenders my app with this.props.activeItemId as 2499.

Example

Using Select.Async and loadOptions I can do a custom filter of the options I want, based on the query. The custom filter I am implementing is based on the value of this.props.activeItemId (so that I can always include it in the filtered options to show up as the selected option at the top of the option results). Like so:

render () {
    return (
       <div className='SomeDiv'>
         <Select.Async
           autoBlur
           searchable
           cache={false}
           clearable={false}
           filterOptions={false} /* using a custom filter */
           backspaceRemoves={false}
           value={this.props.activeItemId}
           onChange={::this.onChange}
           loadOptions={::this.getItems}
         />
       </div>
   )
}

getItems (query, callback) {
  let options = this.someCustomFilter(query)
  return callback(null, { options })
}

someCustomFilter (query) {
  let result = this.props.items
  result = someFilterBasedOnQuery(query)
  result = _.take(result, 20)
  /**
   * When an item is active that isn't contained in the most relevant 20
   * we want to include at the top of the options, so it can appear as active
   */
  if (!query || query === '' && !_.findWhere(result, {id: this.props.activeItemId})) {
    result.unshift(_.findWhere(this.props.items, {id: this.props.activeItemId}))
  }
  return result
}

Issue

When Select.Async receives a new props on rerender, it doesn't re-call loadOptions again, with the new props (activeItemId 2499) so I end up with a select box, with no active item, since the filtered options aren't up to date.

Solution

I made this PR in my own fork to show you the proposed change to 'react-select/src/Async.js' https://github.com/alexjesp/react-select/pull/1/files

Please let me know if you think the solution is valid, if so, I can PR it against this repo (I just didn't want to pollute your PRs). The change doesn't break current tests.

Thanks for any help!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions