|
1 | 1 | import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; |
| 2 | +import { toast } from "@/components/ui/use-toast"; |
| 3 | +import { useEffect, useState } from "react"; |
2 | 4 |
|
3 | 5 | interface Props { |
4 | 6 | options: string[] |
| 7 | + setOptions: (options: string[]) => void |
5 | 8 | selectedValue: string |
6 | 9 | onSelectedValue: (value: string) => void |
7 | 10 |
|
8 | 11 | } |
9 | 12 |
|
10 | | -export default function Combobox({ options, selectedValue, onSelectedValue }: Props) { |
| 13 | +export default function Combobox({ options, setOptions, selectedValue, onSelectedValue }: Props) { |
| 14 | + |
| 15 | + const [open, setOpen] = useState(false) |
| 16 | + const [lastOpened, setLastOpened] = useState<number>(); |
| 17 | + |
| 18 | + const fetchOptions = async () => { |
| 19 | + const result = await fetch(`/api/repo`, { |
| 20 | + method: 'GET', |
| 21 | + }) |
| 22 | + |
| 23 | + if (!result.ok) { |
| 24 | + toast({ |
| 25 | + variant: "destructive", |
| 26 | + title: "Uh oh! Something went wrong.", |
| 27 | + description: await result.text(), |
| 28 | + }) |
| 29 | + return |
| 30 | + } |
| 31 | + |
| 32 | + const json = await result.json() |
| 33 | + setOptions(json.result) |
| 34 | + } |
| 35 | + |
| 36 | + useEffect(() => { |
| 37 | + fetchOptions() |
| 38 | + }, []) |
| 39 | + |
| 40 | + useEffect(() => { |
| 41 | + if (!open) return |
| 42 | + |
| 43 | + const now = Date.now(); |
| 44 | + |
| 45 | + if (lastOpened && now - lastOpened < 30000) return; |
| 46 | + |
| 47 | + setLastOpened(now); |
| 48 | + |
| 49 | + fetchOptions() |
| 50 | + }, [open]) |
| 51 | + |
11 | 52 | return ( |
12 | | - <Select value={selectedValue} onValueChange={onSelectedValue}> |
| 53 | + <Select open={open} onOpenChange={setOpen} value={selectedValue} onValueChange={onSelectedValue}> |
13 | 54 | <SelectTrigger className="rounded-md border focus:ring-0 focus:ring-offset-0"> |
14 | 55 | <SelectValue placeholder="Select a repo" /> |
15 | 56 | </SelectTrigger> |
|
0 commit comments