tyler4949
tyler4949
Explore posts from servers
TTCTheo's Typesafe Cult
Created by tyler4949 on 12/24/2024 in #questions
shadcn Dialog - "submit" vs "cancel"
I am working with a shadcn dialog and I want to execute different functionality when different actions happen. Specifically, I have a form in the modal and I have a save button, which I obviously want to make an API call. However, you can also close the modal by clicking on the backdrop and the built in close button. I want to be able to reset my form when I select the backdrop/close button and execute the API call on click of the save button. As far as I know, theres no way to distinguish between the method of closing the Dialog, any ideas?
3 replies
TTCTheo's Typesafe Cult
Created by tyler4949 on 4/11/2024 in #questions
P3005 Error running Prisma migrate
I am working on a NextJS project that uses prisma. I was able to define my initial schemas and deploy my initial migrations successfully. I made a small change in the diff screenshot attached to this message and I am able to run npx run db push with no issues. When I try to run npx prisma migrate dev to generate a migration, I get the following error:
Error: P3005

The database schema is not empty. Read more about how to baseline an existing production database: https://pris.ly/d/migrate-baseline
Error: P3005

The database schema is not empty. Read more about how to baseline an existing production database: https://pris.ly/d/migrate-baseline
I ran the suggested commands on the baselining docs and while this worked I lost all the data in my db. This is not a huge deal because it was just test data while I learn Prisma, but how can I ensure this doesn't happen again as my project scales? Also, following the steps in the docs didnt regenerate a new migration_lock.toml file. This is also an issue, correct? Any ideas what I did wrong?
2 replies
TTCTheo's Typesafe Cult
Created by tyler4949 on 2/23/2024 in #questions
Postgres DB Wiped?
I set up a postgres db in Vercel to follow Theo's t3 tutorial. I haven't worked on it in a few weeks but just went to look at it and it said I had no data. When I tried to run the prisma studio I got an error saying it couldnt run a query to get a count of undefined (assuming all tables have been removed). I ran npx prisma migrate dev and the table structure is now working but all data is obviously gone and a few new files have been created (migration file and migration lock file) I have no idea how this happened and didn't lose anything important, but is there any way to see the history of the db to see what couldve happened so it doesnt happen again?
2 replies
TTCTheo's Typesafe Cult
Created by tyler4949 on 2/2/2024 in #questions
Prisma generated type missing joined schema in exported type
I am new to Prisma and trying to generate a type based on my prisma schema. The type seems to export correctly, except its missing the value that joins from another schema. For example, I have a Recipe schema with an ingredients array that references another schema, and ingredients is missing. This is a workaround I found, but this feels like it defeats the purpose of the exported types if I am assuming ingredients exists on the recipe object? I feel like I am missing something and shouldnt have to construct the type in my ts files. Is there any way to enforce nested objects be included?
export type Recipe = Prisma.RecipeGetPayload<{
include: { ingredients: true };
}>;
export type Recipe = Prisma.RecipeGetPayload<{
include: { ingredients: true };
}>;
I will include my schemas and exported types below: Schemas
model Recipe {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt

name String
description String @db.VarChar(255)
instructions String @db.VarChar(255)
authorId String

ingredients IngredientInRecipe[]
@@index([authorId])
}

model Ingredient {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt

name String @unique

recipes IngredientInRecipe[]
}

model IngredientInRecipe {
ingredientId String @default(cuid())
recipeId String @default(cuid())
name String
quantity Int
unit String

ingredient Ingredient @relation(fields: [ingredientId], references: [id])
recipe Recipe @relation(fields: [recipeId], references: [id])

@@id([ingredientId, recipeId])
}
model Recipe {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt

name String
description String @db.VarChar(255)
instructions String @db.VarChar(255)
authorId String

ingredients IngredientInRecipe[]
@@index([authorId])
}

model Ingredient {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt

name String @unique

recipes IngredientInRecipe[]
}

model IngredientInRecipe {
ingredientId String @default(cuid())
recipeId String @default(cuid())
name String
quantity Int
unit String

ingredient Ingredient @relation(fields: [ingredientId], references: [id])
recipe Recipe @relation(fields: [recipeId], references: [id])

@@id([ingredientId, recipeId])
}
Exported Recipe Type
type Recipe = {
id: string;
createdAt: Date;
updatedAt: Date;
name: string;
description: string;
instructions: string;
authorId: string;
}
type Recipe = {
id: string;
createdAt: Date;
updatedAt: Date;
name: string;
description: string;
instructions: string;
authorId: string;
}
2 replies
TTCTheo's Typesafe Cult
Created by tyler4949 on 1/13/2024 in #questions
Update local data from useQuery
am using trpc to make a query to load recipe information in my nextjs application: const { data, isLoading } = api.recipes.getDetails.useQuery({ id: id }); I also have a mutation to update the recipe: const { mutateAsync: updateRecipe } = api.recipes.update.useMutation({}); How can I update the local state of data (that comes from the getDetails query) without having to refetch that data once the mutation response comes back? Here is my mutation handler:
await updateRecipe(updatedRecipe, {
onSuccess(data, variables, context) {
console.log(JSON.stringify(data));
!!data && updateLocalData();
},
});
await updateRecipe(updatedRecipe, {
onSuccess(data, variables, context) {
console.log(JSON.stringify(data));
!!data && updateLocalData();
},
});
I would like to implement updateLocalData() but not sure how to set the data without refetching
8 replies
TTCTheo's Typesafe Cult
Created by tyler4949 on 12/23/2023 in #questions
Accessing NEXT_PUBLIC_VERCEL_URL on Front End
TLDR: I am not able to set an env var to process.env.NEXT_PUBLIC_VERCEL_URL in my env.mjs file but when I try to directly access process.env.NEXT_PUBLIC_VERCEL_URL in my front end it works, so I know that is a valid env var. I tried to follow the same approach as accessing VERCEL_URL on the server env object from the default implementation below: Server env Object
server: {
NEXTAUTH_URL: z.preprocess(
// This makes Vercel deployments not fail if you don't set NEXTAUTH_URL
// Since NextAuth.js automatically uses the VERCEL_URL if present.
(str) => process.env.VERCEL_URL ?? str,
// VERCEL_URL doesn't include `https` so it cant be validated as a URL
process.env.VERCEL ? z.string().min(1) : z.string().url(),
),
...otherEnvVars
},
server: {
NEXTAUTH_URL: z.preprocess(
// This makes Vercel deployments not fail if you don't set NEXTAUTH_URL
// Since NextAuth.js automatically uses the VERCEL_URL if present.
(str) => process.env.VERCEL_URL ?? str,
// VERCEL_URL doesn't include `https` so it cant be validated as a URL
process.env.VERCEL ? z.string().min(1) : z.string().url(),
),
...otherEnvVars
},
And then accessing it in my auth.ts file like this: env.NEXTAUTH_URL. This works fine. When I follow a similar approach to access the var assigned to NEXT_PUBLIC_VERCEL_URL var provided on vercel deployments, I get this error: Application error: a client-side exception has occurred (see the browser console for more information). saying that my NEXT_PUBLIC_NEXTAUTH_URL env var is invalid. Here is how I am trying to do this: Client env Object
client: {
NEXT_PUBLIC_NEXTAUTH_URL: z.preprocess(
(str) => process.env.NEXT_PUBLIC_VERCEL_URL ?? str,
// VERCEL_URL doesn't include `https` so it cant be validated as a URL
process.env.VERCEL ? z.string().min(1) : z.string().url(),
),
...otherEnvVars
},
client: {
NEXT_PUBLIC_NEXTAUTH_URL: z.preprocess(
(str) => process.env.NEXT_PUBLIC_VERCEL_URL ?? str,
// VERCEL_URL doesn't include `https` so it cant be validated as a URL
process.env.VERCEL ? z.string().min(1) : z.string().url(),
),
...otherEnvVars
},
I am setting the server and client env vars the same:
runtimeEnv: {
NEXTAUTH_URL: process.env.NEXTAUTH_URL,
NEXT_PUBLIC_NEXTAUTH_URL: process.env.NEXT_PUBLIC_NEXTAUTH_URL,
},
runtimeEnv: {
NEXTAUTH_URL: process.env.NEXTAUTH_URL,
NEXT_PUBLIC_NEXTAUTH_URL: process.env.NEXT_PUBLIC_NEXTAUTH_URL,
},
2 replies
TTCTheo's Typesafe Cult
Created by tyler4949 on 12/20/2023 in #questions
Adding custom value to NextAuth session - [next-auth][error][JWT_SESSION_ERROR]
I am trying to add a username field to my NextAuth session data in my t3 app and am getting the following error: https://next-auth.js.org/errors#jwt_session_error Cannot read properties of undefined (reading 'username') I have added an optional username field to both my User and Session overrides like this:
declare module "next-auth" {
interface Session extends DefaultSession {
user: DefaultSession["user"] & {
id: string;
// ...other properties
username?: string;
// role: UserRole;
};
}

interface User extends DefaultUser {
username?: string;
// ...other properties
// role: UserRole;
}
}
declare module "next-auth" {
interface Session extends DefaultSession {
user: DefaultSession["user"] & {
id: string;
// ...other properties
username?: string;
// role: UserRole;
};
}

interface User extends DefaultUser {
username?: string;
// ...other properties
// role: UserRole;
}
}
And here are my session and jwt callbacks:
callbacks: {
session({ session, token, user }) {
return {
...session,
user: {
...session.user,
id: token.sub,
username: user.username,
},
};
},
jwt({ token, user }) {
console.log("USER: ", user);
return { ...token, user };
},
},
callbacks: {
session({ session, token, user }) {
return {
...session,
user: {
...session.user,
id: token.sub,
username: user.username,
},
};
},
jwt({ token, user }) {
console.log("USER: ", user);
return { ...token, user };
},
},
The strange part is the log in the jwt callback logs the correct user obejct (with the username) once, then logs undefined, and then logs the error above. Any idea why my user would be getting set to undefined and passed into the jwt callback? (logs below)
USER: {
id: ${userIdFromDb},
email: null,
image: null,
username: 'newuser'
}
USER: undefined
[next-auth][error][JWT_SESSION_ERROR]
USER: {
id: ${userIdFromDb},
email: null,
image: null,
username: 'newuser'
}
USER: undefined
[next-auth][error][JWT_SESSION_ERROR]
44 replies
TTCTheo's Typesafe Cult
Created by tyler4949 on 12/17/2023 in #questions
Setting up public env vars in t3 app
I am following the docs (https://create.t3.gg/en/usage/env-variables) for setting up env vars in a t3 app. I have successfully added server env vars but I am having trouble adding client env vars. I am getting the following error Invalid environment variables: { NEXT_PUBLIC_NEXTAUTH_URL: ["Required"] } even though I have this var set up. If I log the env object it seems to be there. Here are my client and runtimeEnv objects in my env.mjs file:
client: {
// NEXT_PUBLIC_CLIENTVAR: z.string().min(1),
NEXT_PUBLIC_NEXTAUTH_URL: z.string(),
},
...
runtimeEnv: {
DATABASE_URL: process.env.DATABASE_URL,
NODE_ENV: process.env.NODE_ENV,
NEXTAUTH_SECRET: process.env.NEXTAUTH_SECRET,
NEXTAUTH_URL: process.env.NEXTAUTH_URL,
NEXT_PUBLIC_NEXTAUTH_URL: process.env.NEXTAUTH_URL,
GOOGLE_CLIENT_ID: process.env.GOOGLE_CLIENT_ID,
GOOGLE_CLIENT_SECRET: process.env.GOOGLE_CLIENT_SECRET,
},
client: {
// NEXT_PUBLIC_CLIENTVAR: z.string().min(1),
NEXT_PUBLIC_NEXTAUTH_URL: z.string(),
},
...
runtimeEnv: {
DATABASE_URL: process.env.DATABASE_URL,
NODE_ENV: process.env.NODE_ENV,
NEXTAUTH_SECRET: process.env.NEXTAUTH_SECRET,
NEXTAUTH_URL: process.env.NEXTAUTH_URL,
NEXT_PUBLIC_NEXTAUTH_URL: process.env.NEXTAUTH_URL,
GOOGLE_CLIENT_ID: process.env.GOOGLE_CLIENT_ID,
GOOGLE_CLIENT_SECRET: process.env.GOOGLE_CLIENT_SECRET,
},
And here is NEXTAUTH_URL in my .env file: NEXTAUTH_URL="http://localhost:3000" Any ideas what I am doing wrong?
4 replies
TTCTheo's Typesafe Cult
Created by tyler4949 on 12/17/2023 in #questions
NextAuth CredentialsProvider User vs Account
I am trying to add a way to login with credentials to my t3 app and don't have very much experience with setting up prisma schemas. It seems that users that create accounts with the GoogleProvider automatically have both a User and an Account item added to their respective tables, but when I use the CredentialsProvider only a User is getting created (not Account). I'm not sure if I am doing something wrong in my schema or create logic (or if this is even necessarily a problem). My schemas are below, I added a username and password field to the User table. I would appreciate any advice/docs to point me in the right direction, thanks!
// Necessary for Next auth
model Account {
id String @id @default(cuid())
userId String
type String
provider String
providerAccountId String
refresh_token String? // @db.Text
access_token String? // @db.Text
expires_at Int?
token_type String?
scope String?
id_token String? // @db.Text
session_state String?
user User @relation(fields: [userId], references: [id], onDelete: Cascade)

@@unique([provider, providerAccountId])
}

model Session {
id String @id @default(cuid())
sessionToken String @unique
userId String
expires DateTime
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
}

model User {
id String @id @default(cuid())
name String?
email String? @unique
emailVerified DateTime?
image String?
accounts Account[]
sessions Session[]

// New fields for local credentials
username String? @unique
password String? // Store the hashed password
}
// Necessary for Next auth
model Account {
id String @id @default(cuid())
userId String
type String
provider String
providerAccountId String
refresh_token String? // @db.Text
access_token String? // @db.Text
expires_at Int?
token_type String?
scope String?
id_token String? // @db.Text
session_state String?
user User @relation(fields: [userId], references: [id], onDelete: Cascade)

@@unique([provider, providerAccountId])
}

model Session {
id String @id @default(cuid())
sessionToken String @unique
userId String
expires DateTime
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
}

model User {
id String @id @default(cuid())
name String?
email String? @unique
emailVerified DateTime?
image String?
accounts Account[]
sessions Session[]

// New fields for local credentials
username String? @unique
password String? // Store the hashed password
}
2 replies
TTCTheo's Typesafe Cult
Created by tyler4949 on 6/9/2023 in #questions
T3 App ESLint Errors
I just created my first t3 app and am getting a ton of Unsafe assignment of an 'any' value linting errors while importing 3rd party libs and using that in my app. All types are imported from the lib so Im not sure why this would be happening. Any idea? Ill include an example of a block of code that is giving this error:
import { configureChains } from "wagmi";
import { publicProvider } from "wagmi/providers/public";
import { mainnet, polygon, optimism, arbitrum, goerli } from "wagmi/chains";

const { chains, publicClient, webSocketPublicClient } = configureChains(
[
mainnet,
polygon,
optimism,
arbitrum,
...(process.env.NEXT_PUBLIC_ENABLE_TESTNETS === "true" ? [goerli] : []),
],
[publicProvider()]
);
import { configureChains } from "wagmi";
import { publicProvider } from "wagmi/providers/public";
import { mainnet, polygon, optimism, arbitrum, goerli } from "wagmi/chains";

const { chains, publicClient, webSocketPublicClient } = configureChains(
[
mainnet,
polygon,
optimism,
arbitrum,
...(process.env.NEXT_PUBLIC_ENABLE_TESTNETS === "true" ? [goerli] : []),
],
[publicProvider()]
);
Errors - Unsafe assignment of an any value. - Unsafe call of an any typed value.
10 replies
TTCTheo's Typesafe Cult
Created by tyler4949 on 6/6/2023 in #questions
Theo and Dan Abramov useEffect Interview Question
I know its old but I am reviewing Theo's practice interview with Dan Abramov (https://www.youtube.com/watch?v=uqII0AOW1NM) and had a question about the autoscroll section. Dan says most people would want to do this in an effect (my first instinct), but Dan said he wouldnt want to do this and you're "not supposed to do things that are disruptive there". Can anyone please explain what the reason for this/link the react docs that explain why this is?
5 replies