omnivore/packages/web/lib/networking/queries/useGetLabelsQuery.tsx

67 lines
1.3 KiB
TypeScript
Raw Normal View History

2022-02-22 10:33:39 +00:00
import { gql } from 'graphql-request'
import useSWR from 'swr'
2022-04-11 01:10:03 +00:00
import { Label, labelFragment } from '../fragments/labelFragment'
2022-02-22 10:33:39 +00:00
import { publicGqlFetcher } from '../networkHelpers'
type LabelsQueryResponse = {
error: any
isLoading: boolean
2022-02-22 10:33:39 +00:00
isValidating: boolean
labels: Label[]
revalidate: () => void
}
type LabelsResponseData = {
labels?: LabelsData
}
type LabelsData = {
labels?: unknown
}
export function useGetLabelsQuery(): LabelsQueryResponse {
const query = gql`
query GetLabels {
labels {
... on LabelsSuccess {
labels {
...LabelFields
2022-02-22 10:33:39 +00:00
}
}
... on LabelsError {
errorCodes
}
}
}
${labelFragment}
2022-02-22 10:33:39 +00:00
`
2023-09-07 11:15:18 +00:00
const { data, error, mutate, isValidating } = useSWR(query, publicGqlFetcher)
2022-02-22 10:33:39 +00:00
try {
if (data && !error) {
2022-02-22 10:33:39 +00:00
const result = data as LabelsResponseData
const labels = result.labels?.labels as Label[]
return {
error,
isLoading: !error && !data,
2022-02-22 10:33:39 +00:00
isValidating,
labels,
revalidate: () => {
mutate()
},
}
}
} catch (error) {
console.log('error', error)
}
return {
error,
isLoading: !error && !data,
2022-02-22 10:33:39 +00:00
isValidating: false,
labels: [],
// eslint-disable-next-line @typescript-eslint/no-empty-function
revalidate: () => {},
}
}