tRPCttRPC
Powered by
Gary, el Pingüino ArtefactoG
tRPC•14mo 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
}
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
tRPCJoin
Move Fast & Break Nothing. End-to-end typesafe APIs made easy.
5,015Members
Resources
Recent Announcements

Similar Threads

Was this page helpful?

Similar Threads

Incorrect type errors
magicsponMmagicspon / ❓-help
3y ago
Make meta in react-query type-safe.
infodushaIinfodusha / ❓-help
2y ago
Type errors in lambda integration
ortonomyOortonomy / ❓-help
3y ago