noctate
noctate
Explore posts from servers
TTCTheo's Typesafe Cult
Created by noctate on 4/17/2023 in #questions
kysely join select query
hey guys im playing with kysely and im trying to get the count of the votes for and votes against, however it seems that only the votedForIds are counted. currently my code looks like this
const query = db
.selectFrom("Anime")
.leftJoin("VoteAnime", "Anime.id", "votedForId")
.select([
"Anime.id",
"Anime.name",
"Anime.imageUrl",
count("VoteAnime.votedForId").as("VoteFor"),
count("VoteAnime.votedAgainstId").as("VoteAgainst"),
])
.groupBy("Anime.id")
.execute();
const query = db
.selectFrom("Anime")
.leftJoin("VoteAnime", "Anime.id", "votedForId")
.select([
"Anime.id",
"Anime.name",
"Anime.imageUrl",
count("VoteAnime.votedForId").as("VoteFor"),
count("VoteAnime.votedAgainstId").as("VoteAgainst"),
])
.groupBy("Anime.id")
.execute();
anyone know how can i fix it? thanks!
9 replies
TTCTheo's Typesafe Cult
Created by noctate on 4/2/2023 in #questions
insert query in kysely, typerror
Hi, I try to migrate from prisma to kysely, only use Prisma for generating the types. Currently I have a insert into db like this with prisma api
ts await ctx.prisma.voteAnime.create({
data: {
votedAgainstId: input.votedAgainst,
votedForId: input.votedFor,
},
});
ts await ctx.prisma.voteAnime.create({
data: {
votedAgainstId: input.votedAgainst,
votedForId: input.votedFor,
},
});
I tried to do it like this with Kysely
ts const result = await ctx.db
.insertInto("VoteAnime")
.values({
votedAgainstId: input.votedAgainst,
votedForId: input.votedFor,
})
.executeTakeFirst();
ts const result = await ctx.db
.insertInto("VoteAnime")
.values({
votedAgainstId: input.votedAgainst,
votedForId: input.votedFor,
})
.executeTakeFirst();
but it gives me errors: Object literal may only specify known properties, and 'votedAgainstId' does not exist in type 'InsertObjectOrListFactory<Database, "VoteAnime">'. Anyone maybe know how to fix this?
4 replies
TTCTheo's Typesafe Cult
Created by noctate on 3/15/2023 in #questions
destructuring assignment typescript error
I have a function getMoveLocation that return array [col, row]. Then I want to use it like this
const [lastCol, lastRow] = getMoveLocation(lastSquares, squares)
const [lastCol, lastRow] = getMoveLocation(lastSquares, squares)
But typescript yells at me
Type 'number[] | undefined' must have a '[Symbol.iterator]()' method that returns an iterator.
Type 'number[] | undefined' must have a '[Symbol.iterator]()' method that returns an iterator.
Anyone maybe know solution?
4 replies
TTCTheo's Typesafe Cult
Created by noctate on 3/12/2023 in #questions
what is this dumb typescript rule
'Unsafe assignment of an any value.' I don't remember it some time ago when creating t3 apps, for example it's yelling at me here:
import ws from 'ws';
const wss = new ws.Server({
port: 3001,
but wss has type? ws.Server<ws.WebSocket>
});
import ws from 'ws';
const wss = new ws.Server({
port: 3001,
but wss has type? ws.Server<ws.WebSocket>
});
2 replies
TTCTheo's Typesafe Cult
Created by noctate on 3/6/2023 in #questions
How to type object like this as props
Heyy I play a little with trpc and optimistic updates and I wonder how can I type object like this when I pass it as props.
const addTodo = api.todos.createTodo.useMutation({
async onMutate(newTodo) {
// Cancel outgoing fetches (so they don't overwrite our optimistic update)
await utils.todos.getAllTodos.cancel();

// Get the data from the queryCache
const prevData = utils.todos.getAllTodos.getData();

// Optimistically update the data with our new post
utils.todos.getAllTodos.setData(
undefined,
(old) => [...(old as Todo[]), newTodo] as Todo[]
);

// Return the previous data so we can revert if something goes wrong
return { prevData };
},
onError(err, newPost, ctx) {
// If the mutation fails, use the context-value from onMutate
utils.todos.getAllTodos.setData(undefined, ctx?.prevData);
},
onSettled() {
// Sync with server once mutation has settled
void utils.todos.getAllTodos.invalidate();
},
});
const addTodo = api.todos.createTodo.useMutation({
async onMutate(newTodo) {
// Cancel outgoing fetches (so they don't overwrite our optimistic update)
await utils.todos.getAllTodos.cancel();

// Get the data from the queryCache
const prevData = utils.todos.getAllTodos.getData();

// Optimistically update the data with our new post
utils.todos.getAllTodos.setData(
undefined,
(old) => [...(old as Todo[]), newTodo] as Todo[]
);

// Return the previous data so we can revert if something goes wrong
return { prevData };
},
onError(err, newPost, ctx) {
// If the mutation fails, use the context-value from onMutate
utils.todos.getAllTodos.setData(undefined, ctx?.prevData);
},
onSettled() {
// Sync with server once mutation has settled
void utils.todos.getAllTodos.invalidate();
},
});
then
const CreateTodo = ({ addTodo }: ???) => {}
const CreateTodo = ({ addTodo }: ???) => {}
6 replies
TTCTheo's Typesafe Cult
Created by noctate on 3/3/2023 in #questions
background gradient shapes
Maybe a weird question but do you know place to get free shapes like this that tailwind ui uses https://keynote.tailwindui.com/
1 replies
TTCTheo's Typesafe Cult
Created by noctate on 2/27/2023 in #questions
docker lags my pc
Heyy I've wanted to try Docker since it's something many people mention, but after installing Docker Desktop when I launch it, it makes my PC lag really bad. I'm on windows 10 and have 8gb RAM, it's not much but I didn't expect it to make it unusable. Anyone know something about this?
16 replies
TTCTheo's Typesafe Cult
Created by noctate on 1/25/2023 in #questions
rewriting table to use react table
Hi! I have my current table but I wonder if its possible to make it work with react table. Im mostly concerned about one part because currently I have a little small icon that let user add Item to favorites (i use trpc to handle that on click)
Tbody
Items.map(Item => (<ItemComponent Item={item}/>)
Tbody
Tbody
Items.map(Item => (<ItemComponent Item={item}/>)
Tbody
Then inside this Item Component I handle the adding / removing stuff. But from what I see react table doesnt work that way so I wonder how should I approach this... will post links to github code in comment below.
2 replies
TTCTheo's Typesafe Cult
Created by noctate on 1/9/2023 in #questions
can u make twitch clone with t3 stack
im just curious if this is possible or not and would the performance be acceptable? not asking how to do that
5 replies
TTCTheo's Typesafe Cult
Created by noctate on 1/9/2023 in #questions
how to delete post if it has likes
Hello lets say I have a post that i want the user to be able to delete, however the post also can have likes. If I use something like this:
delete: protectedProcedure
.input(z.object({
postId: z.string(),
}))
.mutation(async ({ctx, input}) => {
await ctx.prisma.post.delete({
where: {
id: input.postId,
}
})
}),
});
delete: protectedProcedure
.input(z.object({
postId: z.string(),
}))
.mutation(async ({ctx, input}) => {
await ctx.prisma.post.delete({
where: {
id: input.postId,
}
})
}),
});
prisma yells at me The change you are trying to make would violate the required relation 'LikeToPost' between the Like and Post models. How to solve that?
8 replies
TTCTheo's Typesafe Cult
Created by noctate on 1/5/2023 in #questions
reduce initial response time
Im building app with T3 stack but initial response time if I enable SSR in trpc is pretty slow. What usually causes it? Im using the whole stack. What are the ways to improve it? https://cryptosito.vercel.app/ This is live website
10 replies
TTCTheo's Typesafe Cult
Created by noctate on 1/3/2023 in #questions
data fetching, loading state, loading skeletons
Hello currently inside my T3 app I fetch the data from external api on the backend and then pass query it inside Homepage.
const { data: recentData } = trpc.recent.getRecent.useQuery();
const { data: trendingData } = trpc.trending.getTrending.useQuery();
const { data: recentData } = trpc.recent.getRecent.useQuery();
const { data: trendingData } = trpc.trending.getTrending.useQuery();
something like that. Then If there is no data, the user sees a loader. Is this the correct approach or should I instead query the data inside specific components that need it? Also most of websites seems to be using the loading skeletons of individual components instead of loaders (spinning circle in my case). Is there a pattern I can follow to build stuff like that.
1 replies
TTCTheo's Typesafe Cult
Created by noctate on 1/2/2023 in #questions
clean way to protect page and redirect
What is the clean way to dont allow not authenticated user access to the page and instead redirect him to sign in?
9 replies
TTCTheo's Typesafe Cult
Created by noctate on 1/1/2023 in #questions
prisma query
Hello let's say we have a user who buys a coin with specific name. For example first he buys one coin with name 'SuperCoin'. Second time he buys other one coin with name 'CoolCoin'. Third time he buys 2 super coins. How to write a query that sums the number of coin bought based on coin name? Example: Super coin - 3 Cool coin - 1
2 replies
TTCTheo's Typesafe Cult
Created by noctate on 11/17/2022 in #questions
Handling duplicates with trpc
Lets say I have an User in Prisma database that has a Coin[] array in his model. Currently I'm doing something like this to display table of all items:
// Create an item
.mutation(async ({ ctx, input }) => {
try {
await ctx.prisma.coin.create({data: ...})}

// Then get all the items
getAll: publicProcedure.query(async ({ ctx }) => {
try {
return await ctx.prisma.coin.findMany({
where: {userId: ctx.session?.user?.id}
// Create an item
.mutation(async ({ ctx, input }) => {
try {
await ctx.prisma.coin.create({data: ...})}

// Then get all the items
getAll: publicProcedure.query(async ({ ctx }) => {
try {
return await ctx.prisma.coin.findMany({
where: {userId: ctx.session?.user?.id}
It works but the problem is that this way, person can add same items multiple times to this array since they all have unique ids. But if I try to make id not unique then if one user adds an item to his array, the rest cant. So im looking for a better way to handle this. Prisma schema for context:
model Coin {
id String @id @default(cuid())
createdAt DateTime @default(now())
name String
other stuff but not important
}
model User {
id String @id @default(cuid())
name String?
email String? @unique
emailVerified DateTime?
image String?
accounts Account[]
sessions Session[]
coins Coin[]
}
model Coin {
id String @id @default(cuid())
createdAt DateTime @default(now())
name String
other stuff but not important
}
model User {
id String @id @default(cuid())
name String?
email String? @unique
emailVerified DateTime?
image String?
accounts Account[]
sessions Session[]
coins Coin[]
}
13 replies
TTCTheo's Typesafe Cult
Created by noctate on 11/17/2022 in #questions
passing object as a props, how to type it
Heyy lets say I have fully typed object from a backend on a page like this
const { data: getCoin } = trpc.coin.getCoin.useQuery({ name: id });
const { data: getCoin } = trpc.coin.getCoin.useQuery({ name: id });
His type looks like this
symbol: string;
name: string;
image: {
large: string;
};
market_cap_rank: number;
links: {
homepage: string[];
...
symbol: string;
name: string;
image: {
large: string;
};
market_cap_rank: number;
links: {
homepage: string[];
...
But now I want to to pass it as prop to a component. Is there a way to not loose types? I mean it's kinda dumb to just create another schema for typescript right? Is there cool way to not loose types there? For example
<CoinInfo getCoin={getCoin} />
<CoinInfo getCoin={getCoin} />
and then
export const CoinInfo = ({ getCoin }) =>
export const CoinInfo = ({ getCoin }) =>
4 replies
TTCTheo's Typesafe Cult
Created by noctate on 11/16/2022 in #questions
Does parsed data improve speed
Hello, let's say I parse data this way. Does it make my website faster / lighter when I use this query in the frontend, because I return just the stuff I want?
const PokemonResult = z.object({
forms: z.array(z.object({
name: z.string(),
url: z.string(),
})),
base_experience: z.number(),
})
const PokemonResult = z.object({
forms: z.array(z.object({
name: z.string(),
url: z.string(),
})),
base_experience: z.number(),
})

And then create a router
export const pokeRouter = router({
getByName: publicProcedure
.input(z.object({ name: z.string()}))
.query(async ({ input }) => {
const pokemon = await fetch(`https://pokeapi.co/api/v2/pokemon/${input.name}`).then(res =>
res.json());
const parsedData = PokemonResult.parse(pokemon);

return parsedData;
}),
})
export const pokeRouter = router({
getByName: publicProcedure
.input(z.object({ name: z.string()}))
.query(async ({ input }) => {
const pokemon = await fetch(`https://pokeapi.co/api/v2/pokemon/${input.name}`).then(res =>
res.json());
const parsedData = PokemonResult.parse(pokemon);

return parsedData;
}),
})
3 replies
TTCTheo's Typesafe Cult
Created by noctate on 11/15/2022 in #questions
Is this waste of space?
Hello lets say I have router
export const coinRouter = router({
getCoin: publicProcedure
.input(z.object({ name: z.any()}))
.query(async ({ input }) => {
const coin:Coin = await fetch(`https://api.coingecko.com/api/v3/coins/${input.name}`).then(res =>
res.json());
return coin
}),
})
export const coinRouter = router({
getCoin: publicProcedure
.input(z.object({ name: z.any()}))
.query(async ({ input }) => {
const coin:Coin = await fetch(`https://api.coingecko.com/api/v3/coins/${input.name}`).then(res =>
res.json());
return coin
}),
})
And I get big chunk of data BUT I am using only a part of this big data. Can I get only the stuff that I am interested in?
7 replies
TTCTheo's Typesafe Cult
Created by noctate on 11/15/2022 in #questions
when to make new component react
After reviewing my stuff I realized that I don't make a lot of components. So my question is when should I make a new component? Also how should i structure my files? Currently src/components but should i make subfolder if projects gets bigger?
8 replies
TTCTheo's Typesafe Cult
Created by noctate on 11/13/2022 in #questions
is trpc + prisma right for my problem
Hello, let's say I want functionality add to favorites in my webapp. I have user session from next auth. Currently I am storing items inside User model in my database and then mutating and displaying items with help of trpc on frontend. But the problem is that all users see the same list of items. I have tried to filter it by user id but the issue is that now if one user adds Item to favorites, the other can not because its already there but filtered. Now I think that maybe I am overcomplicating it and should just use state management like zustand with local storage?
8 replies