Skip to content

Instantly share code, notes, and snippets.

@colevoss
Created September 21, 2017 16:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save colevoss/a8b90f9596605d2bc5d2e333192e0eb1 to your computer and use it in GitHub Desktop.
Save colevoss/a8b90f9596605d2bc5d2e333192e0eb1 to your computer and use it in GitHub Desktop.
Async Select Options
import React from 'react';
import { Select } from 'uniform';
class SomeForm extends React.Component {
constructor(props) {
super(props);
this.state = {
favStarwarsCharacter: null,
isLoadingOptions: false,
options: [],
};
}
toggleIsLoadingOptions() {
this.setState({
isLoadingOptions: !this.state.isLoadingOptions,
});
}
async fetchOptions() {
if (this.state.options.length) return;
this.toggleIsLoadingOptions();
const swapiRes = await fetch('https://swapi.co/api/people');
const swapiResJson = await swapiRes.json();
const options = swapiResJson.results.map(character => ({
label: character.name,
value: character.name.toLowerCase().replace(/\W/, ''),
}));
this.setState(
{
options,
},
this.toggleIsLoadingOptions
);
}
render() {
return (
<Select
name="fav-star-wars-character"
qaId="qa-fav-star-wars-character"
id="fav-star-wars-character-select"
options={this.state.options}
onOpen={this.fetchOptions}
isLoading={this.state.isLoadingOptions}
placeholder="Select your favorite Star Wars character"
value={t
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment