saleor-dashboard/src/storybook/mock.tsx

66 lines
1.4 KiB
TypeScript
Raw Normal View History

2019-08-09 10:26:22 +00:00
import React from "react";
2019-06-19 14:40:52 +00:00
interface ChoiceProviderProps {
2019-10-14 11:57:08 +00:00
children: (props: {
choices: Array<{
label: string;
value: string;
}>;
loading: boolean;
fetchChoices(value: string);
}) => React.ReactElement<any>;
2019-06-19 14:40:52 +00:00
choices: Array<{
label: string;
value: string;
}>;
}
interface ChoiceProviderState {
choices: Array<{
label: string;
value: string;
}>;
loading: boolean;
timeout: any;
}
export class ChoiceProvider extends React.Component<
ChoiceProviderProps,
ChoiceProviderState
> {
state = { choices: [], loading: false, timeout: null };
2019-10-14 11:57:08 +00:00
handleChange = (inputValue: string) => {
2019-06-19 14:40:52 +00:00
if (this.state.loading) {
clearTimeout(this.state.timeout);
}
const timeout = setTimeout(() => this.fetchChoices(inputValue), 500);
this.setState({
loading: true,
timeout
});
};
2019-10-14 11:57:08 +00:00
fetchChoices = (inputValue: string) => {
2019-06-19 14:40:52 +00:00
this.setState({
2019-10-14 11:57:08 +00:00
choices: this.props.choices
.filter(
suggestion =>
!inputValue ||
2019-06-19 14:40:52 +00:00
suggestion.label.toLowerCase().indexOf(inputValue.toLowerCase()) !==
2019-10-14 11:57:08 +00:00
-1
)
.slice(0, 10),
2019-06-19 14:40:52 +00:00
loading: false,
timeout: null
});
};
render() {
return this.props.children({
choices: this.state.choices,
fetchChoices: this.handleChange,
loading: this.state.loading
});
}
}