Skip to content

Instantly share code, notes, and snippets.

@wcastand
Created September 25, 2024 14:54
Show Gist options
  • Save wcastand/d598abcd456f4d228f2a8c4ea32f0b49 to your computer and use it in GitHub Desktop.
Save wcastand/d598abcd456f4d228f2a8c4ea32f0b49 to your computer and use it in GitHub Desktop.
export const useOneTimeLoggedQuery = <Data = any, Variables extends AnyVariables = AnyVariables>(
document: TypedDocumentNode<Data, Variables>,
variables?: Variables,
opts?: Partial<OperationContext>,
) => {
const [state, setState] = useState<[NonNullable<Data> | undefined, Error | undefined]>([undefined, undefined])
const [client, isLogged] = useAuthSession(useShallow((s) => [s.client, s.isLogged]))
const isConnected = isLogged
const handler = async () => {
const result = await client.query<Data, Variables>(document, variables ?? ({} as Variables), opts).toPromise()
if (!result) setState([undefined, undefined])
else if (result.error) {
console.error(result.error)
DdRum.addError(result.error.message, ErrorSource.CUSTOM, result.error.stack ?? "no stack", {
source: `useOneTimeLoggedQuery - ${getOperationName(document)}`,
})
setState([undefined, result.error])
} else if (!result.data) setState([undefined, new Error("No data")])
else setState([result.data, undefined])
}
useEffect(() => {
if (!isConnected) return
handler()
}, [isConnected])
return [...state, handler] as const
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment