Liltripple_reid
Liltripple_reid
Explore posts from servers
TtRPC
Created by Liltripple_reid on 4/11/2024 in #❓-help
trpc optimistic updates causing data flicker
this is the flicker I'm referring to when updating an entry
5 replies
TtRPC
Created by Liltripple_reid on 4/11/2024 in #❓-help
trpc optimistic updates causing data flicker
const utils = api.useUtils();
const { data: events } = api.entries.getByMonth.useQuery(
{ workspaceId, monthDate: format(month, "yyyy/MM") },
{
initialData,
refetchOnWindowFocus: false,
refetchOnReconnect: false,
},
);

const { mutate } = api.entries.update.useMutation({
onMutate: async (input) => {
await utils.entries.getByMonth.cancel();
const prev = utils.entries.getByMonth.getData({ workspaceId, monthDate });

if (!prev || !auth) return;

const updatedEvent = {
...prev.find((e) => e.id === input.id)!,
...input,
temp: true,
};

utils.entries.getByMonth.setData({ workspaceId, monthDate }, (prevState) => {
if (!prevState) return [];

return [...prevState.filter((e) => e.id !== updatedEvent.id), updatedEvent];
});

return () => utils.entries.getByMonth.setData({ workspaceId, monthDate }, prev);
},
onSettled: () => {
return utils.entries.getByMonth.invalidate({
workspaceId,
monthDate,
});
},
onError: (error, _variables, rollback) => {
toast.error("Something happened, please try again!", {
description: error.message,
});

if (rollback) {
rollback();
}
},
});
const utils = api.useUtils();
const { data: events } = api.entries.getByMonth.useQuery(
{ workspaceId, monthDate: format(month, "yyyy/MM") },
{
initialData,
refetchOnWindowFocus: false,
refetchOnReconnect: false,
},
);

const { mutate } = api.entries.update.useMutation({
onMutate: async (input) => {
await utils.entries.getByMonth.cancel();
const prev = utils.entries.getByMonth.getData({ workspaceId, monthDate });

if (!prev || !auth) return;

const updatedEvent = {
...prev.find((e) => e.id === input.id)!,
...input,
temp: true,
};

utils.entries.getByMonth.setData({ workspaceId, monthDate }, (prevState) => {
if (!prevState) return [];

return [...prevState.filter((e) => e.id !== updatedEvent.id), updatedEvent];
});

return () => utils.entries.getByMonth.setData({ workspaceId, monthDate }, prev);
},
onSettled: () => {
return utils.entries.getByMonth.invalidate({
workspaceId,
monthDate,
});
},
onError: (error, _variables, rollback) => {
toast.error("Something happened, please try again!", {
description: error.message,
});

if (rollback) {
rollback();
}
},
});
this is the part that's controlling the optimistic update
5 replies
TtRPC
Created by Liltripple_reid on 4/11/2024 in #❓-help
trpc optimistic updates causing data flicker
5 replies
TtRPC
Created by Sophia on 3/11/2024 in #❓-help
TRPC useQuery() in NextJS full stack with TypeScript
@Sophia the repo doesn't exist anymore it seems
3 replies
TtRPC
Created by Liltripple_reid on 3/4/2024 in #❓-help
persistedQueries & indexedDb
any suggestions feedback or if anyone finds it useful is appreciated
4 replies
TtRPC
Created by Liltripple_reid on 3/4/2024 in #❓-help
persistedQueries & indexedDb
// react.tsx file created by the t3-app scaffolder and modified to include the persister
"use client";

import { QueryClient } from "@tanstack/react-query";
import { loggerLink, unstable_httpBatchStreamLink } from "@trpc/client";
import { createTRPCReact } from "@trpc/react-query";
import { useState } from "react";

import { PersistQueryClientProvider } from "@tanstack/react-query-persist-client";
import { type AppRouter } from "~/server/api/root";
import { createIDBPersister } from "./persister";
import { getUrl, transformer } from "./shared";

export const api = createTRPCReact<AppRouter>();
const persister = createIDBPersister();

export function TRPCReactProvider(props: { children: React.ReactNode }) {
const [queryClient] = useState(
() =>
new QueryClient({
defaultOptions: {
queries: {
cacheTime: 1000 * 60 * 60 * 5,
},
},
}),
);

const [trpcClient] = useState(() =>
api.createClient({
transformer,
links: [
loggerLink({
enabled: (op) =>
process.env.NODE_ENV === "development" ||
(op.direction === "down" && op.result instanceof Error),
}),
unstable_httpBatchStreamLink({
url: getUrl(),
}),
],
}),
);

return (
<PersistQueryClientProvider
client={queryClient}
persistOptions={{ persister, maxAge: 1000 * 60 * 60 * 4, buster: "persisted-indexed-db" }}
>
<api.Provider client={trpcClient} queryClient={queryClient}>
{props.children}
</api.Provider>
</PersistQueryClientProvider>
);
}
// react.tsx file created by the t3-app scaffolder and modified to include the persister
"use client";

import { QueryClient } from "@tanstack/react-query";
import { loggerLink, unstable_httpBatchStreamLink } from "@trpc/client";
import { createTRPCReact } from "@trpc/react-query";
import { useState } from "react";

import { PersistQueryClientProvider } from "@tanstack/react-query-persist-client";
import { type AppRouter } from "~/server/api/root";
import { createIDBPersister } from "./persister";
import { getUrl, transformer } from "./shared";

export const api = createTRPCReact<AppRouter>();
const persister = createIDBPersister();

export function TRPCReactProvider(props: { children: React.ReactNode }) {
const [queryClient] = useState(
() =>
new QueryClient({
defaultOptions: {
queries: {
cacheTime: 1000 * 60 * 60 * 5,
},
},
}),
);

const [trpcClient] = useState(() =>
api.createClient({
transformer,
links: [
loggerLink({
enabled: (op) =>
process.env.NODE_ENV === "development" ||
(op.direction === "down" && op.result instanceof Error),
}),
unstable_httpBatchStreamLink({
url: getUrl(),
}),
],
}),
);

return (
<PersistQueryClientProvider
client={queryClient}
persistOptions={{ persister, maxAge: 1000 * 60 * 60 * 4, buster: "persisted-indexed-db" }}
>
<api.Provider client={trpcClient} queryClient={queryClient}>
{props.children}
</api.Provider>
</PersistQueryClientProvider>
);
}
4 replies
TtRPC
Created by Liltripple_reid on 10/23/2023 in #❓-help
force-cache planetscale error
if it were related to the DB, querying it directly from RSCs shouldn't work, but it does, PS: I'm using drizzle and the @planetscale/database driver
4 replies
TtRPC
Created by Liltripple_reid on 9/4/2023 in #❓-help
useMutation throwing 500 errors
wait that's weird are you using app/api/<your_route_name>/route.ts or with trpc app/api/trpc/[trpc]/route.ts?
12 replies
TtRPC
Created by Liltripple_reid on 9/4/2023 in #❓-help
useMutation throwing 500 errors
okay after digging more into this I think I found the issue, probably the return data of the router mutation isn't being sent as Response, just tried it on a standalone api route handler and this works: so a) it's not my db, b) probably the adapter used is not parsing the responses?
export const POST = async (req: Request) => {
const body = (await req.json()) as unknown;
const parsed = userPickedSchema.safeParse(body);

const session = await getServerSession(authOptions);

if (!session?.user) {
return new TRPCError({
code: "UNAUTHORIZED",
message: "Unauthorized",
});
}

if (!parsed.success) {
return new TRPCError({
code: "BAD_REQUEST",
message: "Invalid body",
});
}

const { user } = session;

const data = await db.update(users).set(parsed.data).where(eq(users.id, user.id));

console.log({ data, parsed, body });

return new Response(JSON.stringify(data), {
status: 200,
headers: {
"Content-Type": "application/json",
},
});
};
export const POST = async (req: Request) => {
const body = (await req.json()) as unknown;
const parsed = userPickedSchema.safeParse(body);

const session = await getServerSession(authOptions);

if (!session?.user) {
return new TRPCError({
code: "UNAUTHORIZED",
message: "Unauthorized",
});
}

if (!parsed.success) {
return new TRPCError({
code: "BAD_REQUEST",
message: "Invalid body",
});
}

const { user } = session;

const data = await db.update(users).set(parsed.data).where(eq(users.id, user.id));

console.log({ data, parsed, body });

return new Response(JSON.stringify(data), {
status: 200,
headers: {
"Content-Type": "application/json",
},
});
};
12 replies
TtRPC
Created by Liltripple_reid on 9/4/2023 in #❓-help
useMutation throwing 500 errors
totally blocked by this tbh
12 replies
TtRPC
Created by Liltripple_reid on 9/4/2023 in #❓-help
useMutation throwing 500 errors
full error thrown from
useMutation({
onError: ...
})
useMutation({
onError: ...
})
TRPCClientError: Unexpected end of JSON input
at TRPCClientError.from (webpack-internal:///(app-pages-browser)/./node_modules/.pnpm/@[email protected]_@[email protected]/node_modules/@trpc/client/dist/TRPCClientError-fef6cf44.mjs:30:16)
at eval (webpack-internal:///(app-pages-browser)/./node_modules/.pnpm/@[email protected]_@[email protected]/node_modules/@trpc/client/dist/httpUtils-ad76b802.mjs:136:81)
TRPCClientError: Unexpected end of JSON input
at TRPCClientError.from (webpack-internal:///(app-pages-browser)/./node_modules/.pnpm/@[email protected]_@[email protected]/node_modules/@trpc/client/dist/TRPCClientError-fef6cf44.mjs:30:16)
at eval (webpack-internal:///(app-pages-browser)/./node_modules/.pnpm/@[email protected]_@[email protected]/node_modules/@trpc/client/dist/httpUtils-ad76b802.mjs:136:81)
12 replies
TtRPC
Created by Liltripple_reid on 9/4/2023 in #❓-help
useMutation throwing 500 errors
traced back the error down to httpUtils as shown in the first screenshot
12 replies
TtRPC
Created by halfmoon on 8/25/2023 in #❓-help
useQuery always fetching when active on page
you can disable refetchOnMount and refreshOnReconnect in the trpc/useQuery options
3 replies
TtRPC
Created by Liltripple_reid on 8/25/2023 in #❓-help
`createCaller` and RSC - with next-auth
so it's safe to use like this, right?
6 replies
TtRPC
Created by Liltripple_reid on 8/25/2023 in #❓-help
`createCaller` and RSC - with next-auth
so with that I'm using it in RSC pages like this
import { getServerSession } from "next-auth";
import { authOptions } from "~/server/auth";
import { serverClient } from "./_trpc/server-client";

export default async function LandingPage() {
const session = await getServerSession(authOptions);
const data = await serverClient({ session }).example.allUsers();

return (
<section>
<h1>Landing Page</h1>

<pre>{JSON.stringify(data)}</pre>
</section>
);
}
import { getServerSession } from "next-auth";
import { authOptions } from "~/server/auth";
import { serverClient } from "./_trpc/server-client";

export default async function LandingPage() {
const session = await getServerSession(authOptions);
const data = await serverClient({ session }).example.allUsers();

return (
<section>
<h1>Landing Page</h1>

<pre>{JSON.stringify(data)}</pre>
</section>
);
}
I'm wondering if returning/creating the caller on every RSC is a good practice, because I read that it's possible that it may execute all middlewares and validations again
6 replies