AlwayzPatrickA
tRPC3y ago
11 replies
AlwayzPatrick

Implementing wsLink causes issues on React

I get an error within the console stating
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'onError')
    at Object.onError (createHooksInternal-f1d4019d.mjs:454:41)
    at Object.error (index.mjs:80:17)
    at Object.error (index.mjs:20:25)
    at Object.error (observable-ade1bad8.mjs:55:21)
    at Object.error (observable-ade1bad8.mjs:55:21)
    at httpBatchLink-cee1f56c.mjs:200:34
Solution
Found my issue! The solution it to change
App.tsx
import routes from "./pages/_routes";
import { RouterProvider } from "react-router-dom"

import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { createWSClient, httpBatchLink, wsLink, splitLink } from '@trpc/client';
import { useState } from 'react';
import { trpc } from '@/util/_trpc';
import Cookies from "js-cookie";

function App() {
    const headers: any = {};
    if (Cookies.get("token")) {
        headers["authorization"] = `Bearer ${Cookies.get("token")}`;
    }

    const ws = createWSClient({
        url: import.meta.env.VITE_WS_TRPC ?? "",
    })
    const [queryClient] = useState(() => new QueryClient());
    const [trpcClient] = useState(() =>
        trpc.createClient({
            links: [
                splitLink({
                    condition(op) {
                        return op.type === "subscription";
                    },
                    true: wsLink({
                        client: ws
                    }),
                    false: httpBatchLink({
                        url: import.meta.env.VITE_API_TRPC ?? "",
                        // You can pass any HTTP headers you wish here
                        async headers() {
                            return {
                                ...headers
                            };
                        },
                    }),
                }),
            ],
        }),
    );

    return (
        <trpc.Provider client={trpcClient} queryClient={queryClient}>
              <QueryClientProvider client={queryClient}>
                <RouterProvider router={routes} fallbackElement={<h1>Loading...</h1>} />
            </QueryClientProvider>
        </trpc.Provider>
    );
}

export default App;

So it has a split link and only split when the operation is a subscription.
Was this page helpful?