aditya
aditya
TTCTheo's Typesafe Cult
Created by aditya on 7/28/2024 in #questions
Need some help with setting up Express with Next
No description
7 replies
TTCTheo's Typesafe Cult
Created by aditya on 6/11/2024 in #questions
Zod not validating file input
z.object({
userId: z.string(),
headerImage: z
.instanceof(File)
.refine((file) => {
return !file || file.size <= MAX_UPLOAD_SIZE;
}, "File size must be less than 2 MB")
.refine((file) => {
return ACCEPTED_FILE_TYPES.includes(file.type);
}, "File must be a PNG"),
// .any(),
}),
z.object({
userId: z.string(),
headerImage: z
.instanceof(File)
.refine((file) => {
return !file || file.size <= MAX_UPLOAD_SIZE;
}, "File size must be less than 2 MB")
.refine((file) => {
return ACCEPTED_FILE_TYPES.includes(file.type);
}, "File must be a PNG"),
// .any(),
}),
this is the zod schema but its throwing "Input not instance of File" im checking that its a file on client also
function uploadFile(e: ChangeEvent<HTMLInputElement>) {
let file;

if (e.target.files) {
file = e.target.files[0];
}

if (file !== undefined) {
console.log(file);
mutate({ userId, headerImage: file });
}
}
function uploadFile(e: ChangeEvent<HTMLInputElement>) {
let file;

if (e.target.files) {
file = e.target.files[0];
}

if (file !== undefined) {
console.log(file);
mutate({ userId, headerImage: file });
}
}
8 replies
TTCTheo's Typesafe Cult
Created by aditya on 6/11/2024 in #questions
Cannot upload files to supabase storage
No description
4 replies
TTCTheo's Typesafe Cult
Created by aditya on 5/17/2024 in #questions
Cannot get data out of Promis.allSettled()
I am trying to get data from db which requires a an array of individual queries like this:
const dbColumns = await ctx.db
.select()
.from(columns)
.where(eq(columns.projectId, projectId));

const promises = dbColumns.map(async (column) => {
const dbItems = await ctx.db
.select()
.from(items)
.where(eq(items.columnId, column.id));

return {
...column,
items: dbItems,
};
});

const columnsWithItems: ColumnWithItems[] = [];

Promise.allSettled(promises)
.then((results) => {
results.map((result) => {
if (result.status === "fulfilled") {
const columnWithItems = result.value;
columnsWithItems.push(columnWithItems);
console.log(columnsWithItems);
}
});
})
.catch((err) => console.error(err));
console.log(columnsWithItems); // empty array


const dbColumns = await ctx.db
.select()
.from(columns)
.where(eq(columns.projectId, projectId));

const promises = dbColumns.map(async (column) => {
const dbItems = await ctx.db
.select()
.from(items)
.where(eq(items.columnId, column.id));

return {
...column,
items: dbItems,
};
});

const columnsWithItems: ColumnWithItems[] = [];

Promise.allSettled(promises)
.then((results) => {
results.map((result) => {
if (result.status === "fulfilled") {
const columnWithItems = result.value;
columnsWithItems.push(columnWithItems);
console.log(columnsWithItems);
}
});
})
.catch((err) => console.error(err));
console.log(columnsWithItems); // empty array


why is this happening?
1 replies
TTCTheo's Typesafe Cult
Created by aditya on 4/2/2024 in #questions
Query Invalidation with trpc not working with React Server Components and App Router
Hi guys, I am trying to do Optimistic updates with trpc but the problem is I am fetching data on the server component using trpc and passing it to client component
const Dashboard = async () => {
noStore();
const session = await getServerAuthSession();

if (!session) {
redirect("/");
}

const dbWallets = await api.wallet.getAll();

return (
const Dashboard = async () => {
noStore();
const session = await getServerAuthSession();

if (!session) {
redirect("/");
}

const dbWallets = await api.wallet.getAll();

return (
and here is the revalidation code
const { mutate, isPending } = api.wallet.create.useMutation({
onSuccess: () => {
toast("Wallet has been created");
void utils.wallet.getAll.invalidate();
setIsOpen(false);
//revalidatePath("/dashboard");
},
});
const { mutate, isPending } = api.wallet.create.useMutation({
onSuccess: () => {
toast("Wallet has been created");
void utils.wallet.getAll.invalidate();
setIsOpen(false);
//revalidatePath("/dashboard");
},
});
Here I've tried with revalidatePath but that also does nothing Please help!!
32 replies
TTCTheo's Typesafe Cult
Created by aditya on 3/19/2024 in #questions
create t3-app not working
No description
6 replies
TTCTheo's Typesafe Cult
Created by aditya on 2/24/2024 in #questions
Next Auth Session timing out
I just created a new T3 project with Drizzle, Next Auth and Supabase. But while working the session keeps timing out and I have to stop the dev server and sign in again for it to work Error logs:
[next-auth][error][adapter_error_getUserByAccount]
https://next-auth.js.org/errors#adapter_error_getuserbyaccount write CONNECT_TIMEOUT aws-0-ap-south-1.pooler.supabase.com:5432 {
message: 'write CONNECT_TIMEOUT aws-0-ap-south-1.pooler.supabase.com:5432',
stack: 'Error: write CONNECT_TIMEOUT aws-0-ap-south-1.pooler.supabase.com:5432\n' +
' at connectTimedOut (webpack-internal:///(rsc)/./node_modules/.pnpm/[email protected]/node_modules/postgres/src/connection.js:181:64)\n' +
' at Timeout.done [as _onTimeout] (webpack-internal:///(rsc)/./node_modules/.pnpm/[email protected]/node_modules/postgres/src/connection.js:725:12)\n' +
' at listOnTimeout (node:internal/timers:566:11)\n' +
' at process.processTimers (node:internal/timers:507:7)',
name: 'Error'
}
[next-auth][error][OAUTH_CALLBACK_HANDLER_ERROR]
https://next-auth.js.org/errors#oauth_callback_handler_error write CONNECT_TIMEOUT aws-0-ap-south-1.pooler.supabase.com:5432 Error: write CONNECT_TIMEOUT aws-0-ap-south-1.pooler.supabase.com:5432
at connectTimedOut (webpack-internal:///(rsc)/./node_modules/.pnpm/[email protected]/node_modules/postgres/src/connection.js:181:64)
at Timeout.done [as _onTimeout] (webpack-internal:///(rsc)/./node_modules/.pnpm/[email protected]/node_modules/postgres/src/connection.js:725:12)
at listOnTimeout (node:internal/timers:566:11)
at process.processTimers (node:internal/timers:507:7) {
name: 'GetUserByAccountError',
code: 'CONNECT_TIMEOUT'
}
[next-auth][error][adapter_error_getUserByAccount]
https://next-auth.js.org/errors#adapter_error_getuserbyaccount write CONNECT_TIMEOUT aws-0-ap-south-1.pooler.supabase.com:5432 {
message: 'write CONNECT_TIMEOUT aws-0-ap-south-1.pooler.supabase.com:5432',
stack: 'Error: write CONNECT_TIMEOUT aws-0-ap-south-1.pooler.supabase.com:5432\n' +
' at connectTimedOut (webpack-internal:///(rsc)/./node_modules/.pnpm/[email protected]/node_modules/postgres/src/connection.js:181:64)\n' +
' at Timeout.done [as _onTimeout] (webpack-internal:///(rsc)/./node_modules/.pnpm/[email protected]/node_modules/postgres/src/connection.js:725:12)\n' +
' at listOnTimeout (node:internal/timers:566:11)\n' +
' at process.processTimers (node:internal/timers:507:7)',
name: 'Error'
}
[next-auth][error][OAUTH_CALLBACK_HANDLER_ERROR]
https://next-auth.js.org/errors#oauth_callback_handler_error write CONNECT_TIMEOUT aws-0-ap-south-1.pooler.supabase.com:5432 Error: write CONNECT_TIMEOUT aws-0-ap-south-1.pooler.supabase.com:5432
at connectTimedOut (webpack-internal:///(rsc)/./node_modules/.pnpm/[email protected]/node_modules/postgres/src/connection.js:181:64)
at Timeout.done [as _onTimeout] (webpack-internal:///(rsc)/./node_modules/.pnpm/[email protected]/node_modules/postgres/src/connection.js:725:12)
at listOnTimeout (node:internal/timers:566:11)
at process.processTimers (node:internal/timers:507:7) {
name: 'GetUserByAccountError',
code: 'CONNECT_TIMEOUT'
}
12 replies
TTCTheo's Typesafe Cult
Created by aditya on 12/2/2023 in #questions
tRPC not invalidating queries called on RSC
I have a Home Component RSC which fetches the data by trpc and passes it to another client component. The problem is when I mutate the data in the client component the original data isn't invalidated My best guess would be because RSC don't get re-rendered . how can I change my approach
10 replies
TTCTheo's Typesafe Cult
Created by aditya on 11/7/2023 in #questions
weird error in input field
cannot type in input field
const [linkInput, setLinkInput] = useState("");

<Input
className="mt-2 border-none placeholder:pl-6"
placeholder="Link to platform"
value={linkInput}
onChange={(e) => {
console.log(e);
setLinkInput(e.target.value);
}}
const [linkInput, setLinkInput] = useState("");

<Input
className="mt-2 border-none placeholder:pl-6"
placeholder="Link to platform"
value={linkInput}
onChange={(e) => {
console.log(e);
setLinkInput(e.target.value);
}}
cannot type in the input field
4 replies
TTCTheo's Typesafe Cult
Created by aditya on 11/3/2023 in #questions
UI and State not same after altering the state
this is my zustand code
export const useZustand = create<AppState>((set) => ({
links: [],
addLink: ({ platform, link }) => {
set((state) => ({
links: [
...state.links,
{
platform,
link,
},
],
}));
},
removeLink: (index) => {
set((state) => {
const newLinks = state.links.filter((_, i) => i !== index);
return {
...state,
links: newLinks,
};
});
},
editLink: ({ index, platform, link }) => {
set((state) => {
const newLinks = state.links;

const ele = newLinks[index];
if (ele) {
if (platform) {
ele.platform = platform;
}
if (link) {
ele.link = link;
}
newLinks[index] = ele;
}

return {
...state,
links: newLinks,
};
});
},
}));
export const useZustand = create<AppState>((set) => ({
links: [],
addLink: ({ platform, link }) => {
set((state) => ({
links: [
...state.links,
{
platform,
link,
},
],
}));
},
removeLink: (index) => {
set((state) => {
const newLinks = state.links.filter((_, i) => i !== index);
return {
...state,
links: newLinks,
};
});
},
editLink: ({ index, platform, link }) => {
set((state) => {
const newLinks = state.links;

const ele = newLinks[index];
if (ele) {
if (platform) {
ele.platform = platform;
}
if (link) {
ele.link = link;
}
newLinks[index] = ele;
}

return {
...state,
links: newLinks,
};
});
},
}));
This is the UI Form.tsx
<div className="flex flex-col gap-y-3">
<Button variant={"outline"} onClick={addLinks} className="mt-2 w-full">
+ Add new Link
</Button>

{links.map((link, idx) => (
<FormLink
key={idx}
index={idx}
platform={link.platform}
link={link.link}
/>
))}
</div>
<div className="flex flex-col gap-y-3">
<Button variant={"outline"} onClick={addLinks} className="mt-2 w-full">
+ Add new Link
</Button>

{links.map((link, idx) => (
<FormLink
key={idx}
index={idx}
platform={link.platform}
link={link.link}
/>
))}
</div>
16 replies
TTCTheo's Typesafe Cult
Created by aditya on 9/25/2023 in #questions
No response returning from api route
I'm making an api route to fetch/create a chatId for a chat room but its not returning any response, what is wrong here?
import type {NextRequest} from "next/server";
import {NextResponse} from "next/server";
import {getAuthSession} from "@/lib/auth";
import {z} from "zod";
import {db} from "@/lib/db";
import {chats} from "@/lib/db/schema";
import {and, eq, or} from "drizzle-orm";

export async function POST(req: NextRequest) {
try {
const session = await getAuthSession();
if (!session) {
return new Response("UNAUTHORIZED", {
status: 401
});
}
const userId = session.user.id;

const body = await req.json();
const {other} = z.object({
other: z.string()
}).parse(body);

const {chatId} = (await db.select({
chatId: chats.id
}).from(chats).where(
or(
and(eq(chats.userId1, userId), eq(chats.userId2, other)),
and(eq(chats.userId1, other), eq(chats.userId2, userId))
)
).limit(1))[0];

// if (chatId) {
// return new Response(JSON.stringify(chatId), {
// status: 200
// });
// }

const res = (await db.insert(chats).values({
userId1: userId,
userId2: other
}).returning({chatId: chats.id}))[0];

// return new Response(JSON.stringify(res.chatId), {
// status: 200
// });
if (chatId !== null) {
return new NextResponse(chatId, {
status: 200
});
} else if (res.chatId) {
return new NextResponse(res.chatId, {
status: 200
});
} else {
return new NextResponse("ERROR", {
status: 500
});
}
} catch (err) {
console.log(err);
}
}
import type {NextRequest} from "next/server";
import {NextResponse} from "next/server";
import {getAuthSession} from "@/lib/auth";
import {z} from "zod";
import {db} from "@/lib/db";
import {chats} from "@/lib/db/schema";
import {and, eq, or} from "drizzle-orm";

export async function POST(req: NextRequest) {
try {
const session = await getAuthSession();
if (!session) {
return new Response("UNAUTHORIZED", {
status: 401
});
}
const userId = session.user.id;

const body = await req.json();
const {other} = z.object({
other: z.string()
}).parse(body);

const {chatId} = (await db.select({
chatId: chats.id
}).from(chats).where(
or(
and(eq(chats.userId1, userId), eq(chats.userId2, other)),
and(eq(chats.userId1, other), eq(chats.userId2, userId))
)
).limit(1))[0];

// if (chatId) {
// return new Response(JSON.stringify(chatId), {
// status: 200
// });
// }

const res = (await db.insert(chats).values({
userId1: userId,
userId2: other
}).returning({chatId: chats.id}))[0];

// return new Response(JSON.stringify(res.chatId), {
// status: 200
// });
if (chatId !== null) {
return new NextResponse(chatId, {
status: 200
});
} else if (res.chatId) {
return new NextResponse(res.chatId, {
status: 200
});
} else {
return new NextResponse("ERROR", {
status: 500
});
}
} catch (err) {
console.log(err);
}
}
6 replies
TTCTheo's Typesafe Cult
Created by aditya on 9/23/2023 in #questions
Drizzle FKey errror
I have a posts table in postgres and it has a parentPost Foreign key to allow posts inside post (something like twitter). Heres the schema.
export const posts = pgTable(
"post",
{
id: text("id").primaryKey().notNull(),
content: varchar("content", {length: 256}).notNull(),
createdAt: timestamp("created_at", {mode: "string"})
.defaultNow()
.notNull(),
authorId: text("author_id")
.notNull()
.references(() => users.id, {
onDelete: "cascade",
}),
parentPost: text("parent_post").default(""),
},
(table) => ({
ParentPostFkey: foreignKey({
columns: [table.parentPost],
foreignColumns: [table.id],
}),
})
);

export const postRelations = relations(posts, ({one, many}) => ({
author: one(users, {
fields: [posts.authorId],
references: [users.id],
}),
posts: many(posts),
likes: many(likes),
stars: many(stars),
}));
export const posts = pgTable(
"post",
{
id: text("id").primaryKey().notNull(),
content: varchar("content", {length: 256}).notNull(),
createdAt: timestamp("created_at", {mode: "string"})
.defaultNow()
.notNull(),
authorId: text("author_id")
.notNull()
.references(() => users.id, {
onDelete: "cascade",
}),
parentPost: text("parent_post").default(""),
},
(table) => ({
ParentPostFkey: foreignKey({
columns: [table.parentPost],
foreignColumns: [table.id],
}),
})
);

export const postRelations = relations(posts, ({one, many}) => ({
author: one(users, {
fields: [posts.authorId],
references: [users.id],
}),
posts: many(posts),
likes: many(likes),
stars: many(stars),
}));
I'm getting this error while inserting into this table
error: insert or update on table "post" violates foreign key constraint "post_parent_post_post_id_fk"
{
length: 260,
severity: 'ERROR',
code: '23503',
detail: 'Key (parent_post)=() is not present in table "post".',
hint: undefined,
position: undefined,
internalPosition: undefined,
internalQuery: undefined,
where: undefined,
schema: 'public',
table: 'post',
column: undefined,
dataType: undefined,
constraint: 'post_parent_post_post_id_fk',
file: 'ri_triggers.c',
line: '2596',
routine: 'ri_ReportViolation'
}
error: insert or update on table "post" violates foreign key constraint "post_parent_post_post_id_fk"
{
length: 260,
severity: 'ERROR',
code: '23503',
detail: 'Key (parent_post)=() is not present in table "post".',
hint: undefined,
position: undefined,
internalPosition: undefined,
internalQuery: undefined,
where: undefined,
schema: 'public',
table: 'post',
column: undefined,
dataType: undefined,
constraint: 'post_parent_post_post_id_fk',
file: 'ri_triggers.c',
line: '2596',
routine: 'ri_ReportViolation'
}
Here's the api code:
await db.insert(posts).values({
id: nanoid(10),
content,
authorId: session.user.id,
});
await db.insert(posts).values({
id: nanoid(10),
content,
authorId: session.user.id,
});
5 replies
TTCTheo's Typesafe Cult
Created by aditya on 8/10/2023 in #questions
How to keep React state and db in sync with each other
I am making a like feature for a post where if user likes the post the counter increases on the ui and registers the like in db but sometimes the like counter goes into negative.
const PostPage: NextPage = ({}) => {
const router = useRouter();
const { slug } = router.query;
const postId = slug as string;
const { data: session, status } = useSession();
const [currentLike, setCurrentLike] = useState<boolean | undefined>(
undefined
);
const [currentStar, setCurrentStar] = useState<boolean | undefined>(
undefined
);
const { data: post } = api.post.getPostById.useQuery({
postId: postId,
});
const [likesAmt, setLikesAmt] = useState(post?.likes.length || 0);
console.log(post?.likes.length, likesAmt);
const [starsAmt, setStarsAmt] = useState(post?.stars.length ?? 0);
const { mutate: toggleLike } = api.post.toggleLike.useMutation({
onMutate: () => {
if (currentLike) {
setCurrentLike(undefined);
setLikesAmt((prev) => {
// if (prev) {
if (prev == 1) {
return 0;
}
return prev - 1;
// }
});
} else {
setCurrentLike(true);
setLikesAmt((prev) => {
// if (prev) {
return prev + 1;
// }
});
}
},
});

useEffect(() => {
if (post) {
post.likes.map((like) => {
if (like.userId === session?.user.id) {
setCurrentLike(true);
}
});
post.stars.map((star) => {
if (star.userId === session?.user.id) {
setCurrentStar(true);
}
});
}
}, [post, session?.user.id]);
const PostPage: NextPage = ({}) => {
const router = useRouter();
const { slug } = router.query;
const postId = slug as string;
const { data: session, status } = useSession();
const [currentLike, setCurrentLike] = useState<boolean | undefined>(
undefined
);
const [currentStar, setCurrentStar] = useState<boolean | undefined>(
undefined
);
const { data: post } = api.post.getPostById.useQuery({
postId: postId,
});
const [likesAmt, setLikesAmt] = useState(post?.likes.length || 0);
console.log(post?.likes.length, likesAmt);
const [starsAmt, setStarsAmt] = useState(post?.stars.length ?? 0);
const { mutate: toggleLike } = api.post.toggleLike.useMutation({
onMutate: () => {
if (currentLike) {
setCurrentLike(undefined);
setLikesAmt((prev) => {
// if (prev) {
if (prev == 1) {
return 0;
}
return prev - 1;
// }
});
} else {
setCurrentLike(true);
setLikesAmt((prev) => {
// if (prev) {
return prev + 1;
// }
});
}
},
});

useEffect(() => {
if (post) {
post.likes.map((like) => {
if (like.userId === session?.user.id) {
setCurrentLike(true);
}
});
post.stars.map((star) => {
if (star.userId === session?.user.id) {
setCurrentStar(true);
}
});
}
}, [post, session?.user.id]);
26 replies
TTCTheo's Typesafe Cult
Created by aditya on 8/8/2023 in #questions
How to prefetch queries with tRPC?
6 replies
TTCTheo's Typesafe Cult
Created by aditya on 6/13/2023 in #questions
Implementing share feature
1 replies
TTCTheo's Typesafe Cult
Created by aditya on 6/3/2023 in #questions
Weird error in trpc procedure
12 replies
TTCTheo's Typesafe Cult
Created by aditya on 4/3/2023 in #questions
WYSIWYG editors for ts
any recoms for WYSIWYG editors which work well with ts like quill and draftjs
16 replies
TTCTheo's Typesafe Cult
Created by aditya on 4/2/2023 in #questions
prefetchInfinite on getServerSideProps using SSG helpers
2 replies
TTCTheo's Typesafe Cult
Created by aditya on 3/31/2023 in #questions
Role bases authentication with Github Provider using next auth
I want to implement a role based authentication like admin, author and reader using next auth and providers like github, so far I've found doing the same using credentials, is it possible with providers like github etc?
20 replies
TTCTheo's Typesafe Cult
Created by aditya on 2/22/2023 in #questions
electron + vite + react template?
does anyone have a template for electron vite and react without non-essenstial plugins.
1 replies