Gary, el Pingüino ArtefactoG
tRPC13mo ago
6 replies
Gary, el Pingüino Artefacto

Type safe errors?

Hi, it's there a way to make something like this in Trpc?
import { useQuery } from "@tanstack/react-query"
import type { InferResponseType } from "hono"

import { honoClient } from "@/utils/hono"

const request = honoClient.api.hono.auth["get-session"].$post
type SuccessResponse = InferResponseType<typeof request, 200>
type ErrorResponse = InferResponseType<typeof request, 400>

export const useAuthSessionQuery = () => {
  const query = useQuery<SuccessResponse, ErrorResponse>({
    queryKey: ["useAuthSessionQuery"],
    queryFn: async ({ signal }) => {
      const response = await request({}, { init: { signal } })
      if (response.status === 400) throw await response.json()
      if (response.status === 500) throw new Error("Internal server error")
      return await response.json()
    },
  })

  return query
}


The idea is to get also the query.error prop also type safe based on the output of the procedure
Was this page helpful?