React-select: [v2] Initial value of an AsyncSelect component

Created on 31 Jul 2018  路  3Comments  路  Source: JedWatson/react-select

In v2 initial values passed to AsyncSelect are ignored (this was working perfectly fine in v1).
This is the code snippet: https://codesandbox.io/s/myyn21r3x8

import React, { Component } from 'react';

import AsyncSelect from 'react-select/lib/Async';
import { colourOptions } from './docs/data';

type State = {
  inputValue: string,
};

const filterColors = (inputValue: string) =>
  colourOptions.filter(i =>
    i.label.toLowerCase().includes(inputValue.toLowerCase())
  );

const loadOptions = (inputValue, callback) => {
  setTimeout(() => {
    callback(filterColors(inputValue));
  }, 1000);
};

export default class WithCallbacks extends Component<*, State> {
  state = { inputValue: '', value: 'ocean' };

  handleInputChange = (newValue: string) => {
    console.log("vacio:", newValue)
    const inputValue = newValue.replace(/\W/g, '');
    this.setState({ inputValue });
    return inputValue;
  };
  handleChange = (v: String) => {
    this.setState({value: v})
  }
  render() {
    return (
      <div>
        <pre>inputValue: "{this.state.inputValue}"</pre>

        <AsyncSelect
          cacheOptions
          loadOptions={loadOptions}
          defaultOptions
          onInputChange={this.handleInputChange}
          onChange={this.handleChange}
          value={this.state.value}
        />
      </div>
    );
  }
}

I want the select to start with "ocean" option selected, but it starts empty.

Most helpful comment

For my code, I wanted to pre-select a value based on a value in the URL query string. After some fighting with lamba functions, I got the following code to return request a single value by ID from the server and set that value after loading.

import React from "react";
import AsyncSelect from 'react-select/lib/Async';
import queryString from 'query-string';
export class CustomerSelect extends React.Component {

constructor(props) {
    super(props);

    this.state = {
        selectValue: '',
    }
}

loadOptions(query, callback) {
    if (query) {
        axios.get('/api/customers/search?search='+encodeURIComponent(query))
            .then(function(response) {
                const items = response.data.data;
                let options = items.map(function(item) {
                    return {
                        value: item.id,
                        label: item.first_name + ' ' + item.last_name + ' (' + item.email + ')',
                    };
                });
                callback(options);
            });
    }
    else {
        var customerID = queryString.parse(location.search).customer;
        if (customerID) {
            axios.get('/api/customers/fetch?id=' + customerID)
            .then((response) => {
                const items = response.data.data;
                let options = items.map(function(item) {
                    return {
                        value: item.id,
                        label: item.first_name + ' ' + item.last_name + ' (' + item.email + ')',
                    };
                });
                callback(options);
                this.setState({selectValue: options[0]});
            });
        }
    }
}

handleItemSelectChange(option) {
    this.setState({selectValue: option});
}

noOptionsMessage() {
    return 'Type to search customers...';
}

checkForPreLoad() {
    var customerID = queryString.parse(location.search).customer;
    if (customerID) {
        return true;
    }
    return false;
}

render() {
    return (
        <div>
            <input type={"hidden"} name={this.props.name} defaultValue={this.state.selectValue ? this.state.selectValue.value : ''} />
            <AsyncSelect
                cacheOptions={true}
                defaultOptions={this.checkForPreLoad()}
                loadOptions={(query, callback) => this.loadOptions(query, callback)}
                onChange={(option) => this.handleItemSelectChange(option)}
                value={ this.state.selectValue }
                noOptionsMessage={ this.noOptionsMessage }
                classNamePrefix="react-Selector"
            />
        </div>
    );
}
}

All 3 comments

Duplicate of #2841

For my code, I wanted to pre-select a value based on a value in the URL query string. After some fighting with lamba functions, I got the following code to return request a single value by ID from the server and set that value after loading.

import React from "react";
import AsyncSelect from 'react-select/lib/Async';
import queryString from 'query-string';
export class CustomerSelect extends React.Component {

constructor(props) {
    super(props);

    this.state = {
        selectValue: '',
    }
}

loadOptions(query, callback) {
    if (query) {
        axios.get('/api/customers/search?search='+encodeURIComponent(query))
            .then(function(response) {
                const items = response.data.data;
                let options = items.map(function(item) {
                    return {
                        value: item.id,
                        label: item.first_name + ' ' + item.last_name + ' (' + item.email + ')',
                    };
                });
                callback(options);
            });
    }
    else {
        var customerID = queryString.parse(location.search).customer;
        if (customerID) {
            axios.get('/api/customers/fetch?id=' + customerID)
            .then((response) => {
                const items = response.data.data;
                let options = items.map(function(item) {
                    return {
                        value: item.id,
                        label: item.first_name + ' ' + item.last_name + ' (' + item.email + ')',
                    };
                });
                callback(options);
                this.setState({selectValue: options[0]});
            });
        }
    }
}

handleItemSelectChange(option) {
    this.setState({selectValue: option});
}

noOptionsMessage() {
    return 'Type to search customers...';
}

checkForPreLoad() {
    var customerID = queryString.parse(location.search).customer;
    if (customerID) {
        return true;
    }
    return false;
}

render() {
    return (
        <div>
            <input type={"hidden"} name={this.props.name} defaultValue={this.state.selectValue ? this.state.selectValue.value : ''} />
            <AsyncSelect
                cacheOptions={true}
                defaultOptions={this.checkForPreLoad()}
                loadOptions={(query, callback) => this.loadOptions(query, callback)}
                onChange={(option) => this.handleItemSelectChange(option)}
                value={ this.state.selectValue }
                noOptionsMessage={ this.noOptionsMessage }
                classNamePrefix="react-Selector"
            />
        </div>
    );
}
}

Hello -

In an effort to sustain the react-select project going forward, we're closing old issues.

We understand this might be inconvenient but in the best interest of supporting the broader community we have to direct our limited efforts to maintain the latest version.

If you aren't using the latest version of react-select please consider upgrading to see if it resolves any issues you're having.

However, if you feel this issue is still relevant and you'd like us to review it - please leave a comment and we'll do our best to get back to you!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

geraldfullam picture geraldfullam  路  3Comments

x-yuri picture x-yuri  路  3Comments

AchinthaReemal picture AchinthaReemal  路  3Comments

mjuopperi picture mjuopperi  路  3Comments

sampatbadhe picture sampatbadhe  路  3Comments