-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathSubnetListbox.tsx
More file actions
62 lines (53 loc) · 1.99 KB
/
SubnetListbox.tsx
File metadata and controls
62 lines (53 loc) · 1.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, you can obtain one at https://mozilla.org/MPL/2.0/.
*
* Copyright Oxide Computer Company
*/
import { useQuery } from '@tanstack/react-query'
import { useWatch, type FieldPath, type FieldValues } from 'react-hook-form'
import { api, q } from '@oxide/api'
import { useProjectSelector } from '~/hooks/use-params'
import { ListboxField, type ListboxFieldProps } from './ListboxField'
type SubnetListboxProps<
TFieldValues extends FieldValues,
TName extends FieldPath<TFieldValues>,
> = Omit<ListboxFieldProps<TFieldValues, TName>, 'items'> & {
vpcNameField: FieldPath<TFieldValues>
}
/**
* Read the selected VPC name from the Formik context and fetch the subnets for
* that VPC. Only fetch if the VPC name is that of an existing VPC.
*
* Needs to be its own component so it can go *inside* the `<Formik>` element in
* order to have access to the context.
*/
export function SubnetListbox<
TFieldValues extends FieldValues,
TName extends FieldPath<TFieldValues>,
>({ vpcNameField, control, ...fieldProps }: SubnetListboxProps<TFieldValues, TName>) {
const projectSelector = useProjectSelector()
const [vpcName] = useWatch({ control, name: [vpcNameField] })
// assume vpc exists if it's non-empty since it came from the listbox
const vpcExists = vpcName.length > 0
// TODO: error handling other than fallback to empty list?
const subnets =
useQuery(
q(
api.vpcSubnetList,
{ query: { ...projectSelector, vpc: vpcName } },
{ enabled: vpcExists, throwOnError: false }
)
).data?.items || []
return (
<ListboxField
{...fieldProps}
items={subnets.map(({ name }) => ({ value: name, label: name }))}
disabled={!vpcExists}
control={control}
placeholder="Select a VPC subnet"
noItemsPlaceholder={vpcName ? 'No subnets found' : 'Select a VPC to see subnets'}
/>
)
}