constraints
constraints
TTCTheo's Typesafe Cult
Created by constraints on 4/23/2023 in #questions
Tailwind seemingly not working randomly when deployed.
6 replies
TTCTheo's Typesafe Cult
Created by constraints on 3/16/2023 in #questions
Noob TRPC quesiton regarding response JSON
I am struggling with parsing some JSON my TRPC API is responding, and hoping to receive some guidance. I have a TRPC API which calls a table created in Prisma , as follows:
const { data: fetchedQuiz,isLoading } = api.quiz.getQuizzesByQuizID.useQuery<>({
quizID:Number.parseInt(gameID as string)
})
const { data: fetchedQuiz,isLoading } = api.quiz.getQuizzesByQuizID.useQuery<>({
quizID:Number.parseInt(gameID as string)
})
As you can see, it is being parsed as a quiz type, this is defined in prisma as follows:
model quiz {
id Int @id @default(autoincrement())
user User @relation(fields: [userId], references: [id])
userId String
quizData Json
score Int
date DateTime
}
model quiz {
id Int @id @default(autoincrement())
user User @relation(fields: [userId], references: [id])
userId String
quizData Json
score Int
date DateTime
}
Now, my problem is I want to access the properties of fetchedQuiz. specifcially, the quizData property. I know this JSON being returned has the properties questions, "correctAns", "selectedAnswers" and "allAnswers". However typescript complains when I try to access these properties, because the JSON isnt defined in Prisma, giving me the error: Property 'questions' does not exist on type 'string | number | boolean | JsonObject | JsonArray' This is obviously because it can't parse the properties of the quizData Json from Prisma. How would you suggest I go about ensuring this can be parsed? Some things I have tried are: Defining my own types for the response which matches the JSON, and then trying to cast the useQuery, as follows:
export interface quizDataType{
questions: string[]
correctAns: string[]
selectedAnswers:string[]
allAnswers:string[][]
}

export interface quizType{
id: number,
userId: string,
quizData: quizDataType,
score: number,
date: string
}
export interface quizDataType{
questions: string[]
correctAns: string[]
selectedAnswers:string[]
allAnswers:string[][]
}

export interface quizType{
id: number,
userId: string,
quizData: quizDataType,
score: number,
date: string
}
const { data: fetchedQuiz, isLoading } = api.quiz.getQuizzesByQuizID.useQuery<quizType>({
quizID: Number.parseInt(gameID as string),
});
const { data: fetchedQuiz, isLoading } = api.quiz.getQuizzesByQuizID.useQuery<quizType>({
quizID: Number.parseInt(gameID as string),
});
But this doesn't work, as fetchedQuiz is still of type quiz. Any suggestions are helpful.
14 replies