Skip to content

Instantly share code, notes, and snippets.

@selbekk
Created July 23, 2018 12:16
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 selbekk/bd8edf909dcf367b6dff12a87f1fa300 to your computer and use it in GitHub Desktop.
Save selbekk/bd8edf909dcf367b6dff12a87f1fa300 to your computer and use it in GitHub Desktop.
An API backed dropdown with Flow types
// @flow
import * as React from 'react';
import { TertiaryButton } from '@sb1/ffe-buttons-react';
import { Paragraph } from '@sb1/ffe-core-react';
import Dropdown from '@sb1/ffe-dropdown-react';
import Spinner from '@sb1/ffe-spinner-react';
import withApiState from '../../hocs/with-api-state';
import type { StateMachine } from '../../hocs/with-api-state';
type Option = {
value: string,
label: string,
};
type Props<ReturnType> = {
apiState: StateMachine,
fetcher: () => Promise<Array<ReturnType>>,
mapper: (input: ReturnType) => Option,
};
type State = {
options: Array<Option>,
};
class ApiBackedDropdown<ReturnType> extends React.Component<Props<ReturnType>, State> {
state = {
options: [],
};
componentDidMount() {
this.fetchData();
}
fetchData = async () => {
const { apiState, fetcher, mapper } = this.props;
try {
apiState.setPending();
const result = await fetcher();
const options = result.map(mapper);
this.setState({ options });
apiState.setSuccess();
} catch (e) {
apiState.setError();
}
};
render() {
const { apiState, ...rest } = this.props;
const { options } = this.state;
if (apiState.isIdle() || apiState.isPending()) {
return (
<Paragraph>
<Spinner /> Vennligst vent
</Paragraph>
);
}
if (apiState.isError()) {
return (
<Paragraph>
Noe gikk feil mens vi hentet data.{' '}
<TertiaryButton type="button" onClick={this.fetchData}>
Prøv igjen
</TertiaryButton>
</Paragraph>
);
}
return (
<Dropdown {...rest}>
{options.map((option) => (
<option key={option.value} value={option.value}>
{option.label}
</option>
))}
</Dropdown>
);
}
}
export default withApiState(ApiBackedDropdown);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment