owdx
owdx

Reputation: 11

'client' is of type 'unknown'.ts(18046) Error -- bun RPC

server/app.ts

export const app = new Hono();

const appRoute = app.basePath("/api").route("/user", userRoutes)

export type AppType = typeof appRoute

client/App.tsx

import { useEffect } from "react"
import { hc } from "hono/client"
import { type AppType } from "../../server/app"

const client = hc<AppType>("/");

function App() {
    useEffect(() => {
        const fetchTotal = async () => {
            const resp = await client.api.user.$get() // client' is of type 'unknown'.ts(18046)
            // ... 

        }
        fetchTotal()
    }, [])

    return (
        // ...
    )
}

export default App

In my vite react application, I'm simply trying to access client.api.user.$get(), however I get the error of client being unknown.

If I were to modify my basePath:

.basePath("/api")
    .get("/", c => {
        return c.json({ message: "It will only see this" })
    })
    .route("/user", userRoutes)

This time, it is going to recognize client.api.$get(), but still client.api.user.$get() will not be recognized.

Upvotes: 1

Views: 157

Answers (1)

Nikola
Nikola

Reputation: 320

At the time of writing this, according to the documentation this is not possible if you don't chain all the methods one after another in a single file. Otherwise you will loose type safety.

From the docs: If you want to use RPC features, a better solution would be chaining the methods as described below

import { Hono } from "hono";

const app = new Hono()
  .get("/", (c) => c.json("list authors"))
  .post("/", (c) => c.json("create an author", 201))
  .get("/:id", (c) => c.json(`get ${c.req.param("id")}`));

export default app;

Hono - Best Practices # Building Large Applications

Upvotes: 0

Related Questions