2035Builder
2035Builder
TtRPC
Created by 2035Builder on 9/5/2024 in #❓-help
TextDecoder not implemented Trpc react-native httpBatchStreamLink
Receiving the stream relies on the TextDecoder and TextDecoderStream APIs, which is not available in React Native. If you still want to enable streaming, you need to polyfill those. any refrence to this?
4 replies
TtRPC
Created by 2035Builder on 8/14/2024 in #❓-help
I notice Authorization is been removed from my header on my dev environment
api.createClient({
transformer: superjson,
links: [
httpBatchLink({
url: `${getBaseUrl()}/api/trpc`,
async headers(header) {
const { data } = await supabase.auth.getSession();
const token = data.session?.access_token;
console.log({ token })
return {
Authorization: `Bearer ${token}`,
'x-trpc-source': 'expo-react',
"app-token": token,

};
},
})
]
})
api.createClient({
transformer: superjson,
links: [
httpBatchLink({
url: `${getBaseUrl()}/api/trpc`,
async headers(header) {
const { data } = await supabase.auth.getSession();
const token = data.session?.access_token;
console.log({ token })
return {
Authorization: `Bearer ${token}`,
'x-trpc-source': 'expo-react',
"app-token": token,

};
},
})
]
})
my server handler [trpc].ts
import type { NextApiHandler, NextApiRequest, NextApiResponse } from "next";
import { createPagesServerClient } from "@supabase/auth-helpers-nextjs";
import { createNextApiHandler } from "@trpc/server/adapters/next";
import Cors from "cors";

import { appRouter, createTRPCContext } from "@lumi/api";

// Initialize CORS middleware
const cors = Cors({
methods: ["GET", "POST", "OPTIONS"],
allowedHeaders: ["Authorization", "Content-Type", 'x-trpc-source', 'app-token'],
origin: '*'
});

// Helper function to run middleware
function runMiddleware(req: NextApiRequest, res: NextApiResponse, fn: any) {
return new Promise<void>((resolve, reject) => {
fn(req, res, (result: any) => {
if (result instanceof Error) {
return reject(result);
}
return resolve();
});
});
}

// Middleware wrapper for CORS
export function withCors(handler: NextApiHandler) {
return async (req: NextApiRequest, res: NextApiResponse) => {
await runMiddleware(req, res, cors);
return handler(req, res);
};
}

// Create TRPC handler
const trpcHandler = createNextApiHandler({
router: appRouter,
createContext: async ({ req, res }) => {
const supabase = createPagesServerClient({ req, res });
const context = createTRPCContext({ req, res, supabase });
return context;
}
});

// Export API route handler with CORS
const handler: NextApiHandler = async (req, res) => {
return withCors(trpcHandler)(req, res);
};

export default handler;
import type { NextApiHandler, NextApiRequest, NextApiResponse } from "next";
import { createPagesServerClient } from "@supabase/auth-helpers-nextjs";
import { createNextApiHandler } from "@trpc/server/adapters/next";
import Cors from "cors";

import { appRouter, createTRPCContext } from "@lumi/api";

// Initialize CORS middleware
const cors = Cors({
methods: ["GET", "POST", "OPTIONS"],
allowedHeaders: ["Authorization", "Content-Type", 'x-trpc-source', 'app-token'],
origin: '*'
});

// Helper function to run middleware
function runMiddleware(req: NextApiRequest, res: NextApiResponse, fn: any) {
return new Promise<void>((resolve, reject) => {
fn(req, res, (result: any) => {
if (result instanceof Error) {
return reject(result);
}
return resolve();
});
});
}

// Middleware wrapper for CORS
export function withCors(handler: NextApiHandler) {
return async (req: NextApiRequest, res: NextApiResponse) => {
await runMiddleware(req, res, cors);
return handler(req, res);
};
}

// Create TRPC handler
const trpcHandler = createNextApiHandler({
router: appRouter,
createContext: async ({ req, res }) => {
const supabase = createPagesServerClient({ req, res });
const context = createTRPCContext({ req, res, supabase });
return context;
}
});

// Export API route handler with CORS
const handler: NextApiHandler = async (req, res) => {
return withCors(trpcHandler)(req, res);
};

export default handler;
2 replies
TtRPC
Created by 2035Builder on 8/10/2024 in #❓-help
ERROR TypeError: queryClient.getMutationDefaults is not a function (it is undefined)
const { mutate: joinChallenge } = api.challenges.join.useMutation();
const handleJoinChallenge = () => {
};
joinChallenge({
challengeId: id,
});
};
const { mutate: joinChallenge } = api.challenges.join.useMutation();
const handleJoinChallenge = () => {
};
joinChallenge({
challengeId: id,
});
};
using version 10.45.2
3 replies
TtRPC
Created by 2035Builder on 8/8/2024 in #❓-help
I commented my query out, but i still notice request are still been made. this is what my code look
I keep getting api request to backend continously even without making api request. my api client
import { useMemo, useCallback } from "react";
import Constants from "expo-constants";
import { useSupabaseClient } from "@supabase/auth-helpers-react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { httpBatchLink, loggerLink, httpLink } from "@trpc/client";
import { createTRPCReact } from "@trpc/react-query";
import superjson from "superjson";

import type { AppRouter } from "@lumi/api";

/**
* A set of typesafe hooks for consuming your API.
*/
export const api = createTRPCReact<AppRouter>();
export { type RouterInputs, type RouterOutputs } from "@lumi/api";


const getBaseUrl = () => {

const debuggerHost = Constants.expoConfig?.hostUri;
const localhost = debuggerHost?.split(":")[0];
console.log("Localhost:", localhost); // Add logging

if (!localhost) {
// return "https://turbo.t3.gg";
throw new Error(
"Failed to get localhost. Please point to your production server.",
);
}
return `http://${localhost}:3000`;
};

/**
* A wrapper for your app that provides the TRPC context.
* Use only in _app.tsx
*/
export const TRPCProvider = (props: { children: React.ReactNode }) => {
const supabase = useSupabaseClient();

const queryClient = useMemo(() => new QueryClient(), []);

const getHeaders = useCallback(async () => {
const headers = new Map<string, string>();
headers.set("x-trpc-source", "expo-react");

const { data } = await supabase.auth.getSession();
const token = data.session?.access_token;
console.log("called multiple times")
if (token) headers.set("authorization", token);

return Object.fromEntries(headers);
}, [supabase]);

const trpcClient = useMemo(
() =>
api.createClient({
transformer: superjson,
links: [
httpLink({
url: `${getBaseUrl()}/api/trpc`,
headers: async () => await getHeaders(),
}),
loggerLink({
enabled: (opts) =>
process.env.NODE_ENV === "development" ||
(opts.direction === "down" && opts.result instanceof Error),
colorMode: "ansi",
onError: (err) => {
console.error("Client-side tRPC error:", err);
},
}),
],
}),
[getHeaders]
);

return (
<api.Provider client={trpcClient} queryClient={queryClient}>
<QueryClientProvider client={queryClient}>
{props.children}
</QueryClientProvider>
</api.Provider>
);
};
import { useMemo, useCallback } from "react";
import Constants from "expo-constants";
import { useSupabaseClient } from "@supabase/auth-helpers-react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { httpBatchLink, loggerLink, httpLink } from "@trpc/client";
import { createTRPCReact } from "@trpc/react-query";
import superjson from "superjson";

import type { AppRouter } from "@lumi/api";

/**
* A set of typesafe hooks for consuming your API.
*/
export const api = createTRPCReact<AppRouter>();
export { type RouterInputs, type RouterOutputs } from "@lumi/api";


const getBaseUrl = () => {

const debuggerHost = Constants.expoConfig?.hostUri;
const localhost = debuggerHost?.split(":")[0];
console.log("Localhost:", localhost); // Add logging

if (!localhost) {
// return "https://turbo.t3.gg";
throw new Error(
"Failed to get localhost. Please point to your production server.",
);
}
return `http://${localhost}:3000`;
};

/**
* A wrapper for your app that provides the TRPC context.
* Use only in _app.tsx
*/
export const TRPCProvider = (props: { children: React.ReactNode }) => {
const supabase = useSupabaseClient();

const queryClient = useMemo(() => new QueryClient(), []);

const getHeaders = useCallback(async () => {
const headers = new Map<string, string>();
headers.set("x-trpc-source", "expo-react");

const { data } = await supabase.auth.getSession();
const token = data.session?.access_token;
console.log("called multiple times")
if (token) headers.set("authorization", token);

return Object.fromEntries(headers);
}, [supabase]);

const trpcClient = useMemo(
() =>
api.createClient({
transformer: superjson,
links: [
httpLink({
url: `${getBaseUrl()}/api/trpc`,
headers: async () => await getHeaders(),
}),
loggerLink({
enabled: (opts) =>
process.env.NODE_ENV === "development" ||
(opts.direction === "down" && opts.result instanceof Error),
colorMode: "ansi",
onError: (err) => {
console.error("Client-side tRPC error:", err);
},
}),
],
}),
[getHeaders]
);

return (
<api.Provider client={trpcClient} queryClient={queryClient}>
<QueryClientProvider client={queryClient}>
{props.children}
</QueryClientProvider>
</api.Provider>
);
};
14 replies
TtRPC
Created by 2035Builder on 4/10/2024 in #❓-help
TRPCClientError: Unable to transform response from server
I am currently encountering this error occasionally in my apps. I am using a Monorepo, which includes a mobile app and two web apps, all connected to a single database using Prisma and using TRPC in all apps. I have been trying to determine the cause of the error, but I still have no idea. I would appreciate it if anyone has any ideas or has experienced this issue before. Thank you
4 replies