Created
July 23, 2018 12:16
-
-
Save selbekk/bd8edf909dcf367b6dff12a87f1fa300 to your computer and use it in GitHub Desktop.
An API backed dropdown with Flow types
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// @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