I encountered an unexpected issue when attempting to retrieve my TAG in Prisma, resulting in an undefined value

Currently diving into the world of CRUD operations in NextJS using TypeScript and Prisma with TanstackQuery. I am facing an issue where I am trying to display the tag.name, but unfortunately, I keep encountering an undefined error when attempting to fetch it.

https://i.sstatic.net/TqTgJ.png

In my Homepage component, I retrieve all the necessary data and pass it down to my <PostCard />.

async function getPost() {
  const response = await db.post.findMany({
    select: {
      id: true,
      title: true,
      content: true,
    },
    orderBy: {
      createdAt: 'desc'
    }
  })

  return response
}

const Home = async () => {
  
  const posts = await getPost();

  return (
    <main>
      {posts.map(post => (
        <PostCard key={post.id} post={post} />
      ))}
    </main>
  );
};

The PostCard component is where I receive the props passed down from my homepage.

import { Tag } from "@prisma/client";
interface PostCardProps {
  post: {
    id: string,
    title: string,
    content:string,
    tag: Tag

  }
}

const PostCard = ({post}:PostCardProps) => {

  const {title, content, tag} = post
  

  return (
    <div>
        <h2 className="card-title">{title}</h2>
        <p>{content}</p>
        <div className="card-actions justify-end">
            <Link href="/blog/1">
                Read more...
            </Link>
        </div>
      </div>
  );
};

Below is my Prisma Schema defining the relationship between post and tags:

model Tag {
  id   String @id @default(cuid())
  name String @db.VarChar(100)
  Post Post[]
}

model Post {
  id    String @id @default(cuid())
  title String @db.VarChar(225)
  content String

  tagId String
  Tag Tag @relation(fields: [tagId], references: [id], onDelete: Cascade)
}

Answer №1

Oh dear, I made a mistake and figured it out now. In my Prisma.Schema file, I mistakenly had

model Post {
  id    String @id @default(cuid())
  title String @db.VarChar(225)
  content String

  tagId String
  Tag Tag @relation(fields: [tagId], references: [id], onDelete: Cascade)
}

I corrected this by changing.

  Tag Tag @relation(fields: [tagId], references: [id], onDelete: Cascade)

to

  tag Tag @relation(fields: [tagId], references: [id], onDelete: Cascade)

Furthermore, I also included.

tag: true

in my GetPosts

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to change the role link in child elements inherited from the parent in terms of Accessibility

How can I create a tooltip with dynamically added tooltip content div requiring a role link for the aria label to be appended as needed? The initial HTML of the tooltip before expansion is: <div class="tooltip" tabindex="0" aria-expa ...

Creating a Cloudinary Angular URL: A Step-by-Step Guide

Currently, I am utilizing Cloudinart on Angular and my goal is to create a Cloudinary URL. <cl-image public-id="public_id"> <cl-transformation height="270" width="480" crop="fill"/> & ...

Enclosing sets of lists with div containers

My Objective: <ul> <li class="group4"> <ul class="group2"> <li class="first">stuff</li> <li class="last">stuff</li> </ul> <ul class="group2"> ...

What are some ways to use SWR for mutating data specific to a certain ID?

I have scoured the internet for answers to no avail. It's baffling because I expected this issue to be quite common. Take, for instance, the scenario where we need to retrieve a post with a specific id: const { data } = useSWR(`/api/post/${id}`, fetc ...

Is there a way I can sort an array by checking if a key exists in an object?

I am currently working with code that filters data based on specific keys - in this case, "bounced" or "opened". Filtering for "bounced" items is working perfectly, but I am facing an issue with "opened" items. The key "opened" only exists if a message has ...

Transferring identification data between views within an application (AngularJS, NodeJs, HTML)

I'm working on an HTML page that lists users from MongoDB. The page allows for deleting and updating users. I am encountering an issue with the update button - I want a new HTML page to appear with a form when the button is clicked, capturing the user ...

What methods can be used to incorporate animation when the display attribute transitions to none?

Is there a way to add animation in a Vue app when replacing elements? I would like the transition from, for example, clicking on a div with 'Num 1' to the divs with class 'showing' not disappear abruptly but smoothly, such as moving to ...

When the page is dynamically loaded, Ng-repeat does not function as expected

I am working on a page that includes the following code snippet: <script> angular.module('myapp', []).controller('categoryCtrl', function($scope) { $scope.category = <? echo json_encode($myarr); ?>; $scope.subcatego ...

Having trouble with the onChange function within the rc-field-form wrapper

I created a wrapper for the Field component from the rc-field-form package as shown below: import * as React from "react"; import Form from "rc-field-form"; import type { FieldProps } from "rc-field-form/lib/Field"; const { F ...

Build a new shop using a section of data from a JSON database

Let's say I have a JSON store that is set up as shown below var subAccountStore = new Ext.data.JsonStore({ autoLoad: true, proxy: { type:'ajax', url : '/opUI/json/subaccount.action?name="ABC"' }, fields: ['acc ...

Guide on how to efficiently navigate and extract data from a (local) XML file using Prototype JS

I'm currently working on a project that already utilizes PrototypeJS and I need to develop a module for it. Here's what I have: - An XML file containing the necessary information Here's what I'm aiming for: - A basic div that showcase ...

Using Angular JS to compare and display the changed value in a textbox from its previous value

This is the code I am working with <body> <div> <table ng-app='myApp' ng-controller="MainCtrl"> <thead></thead> <tbody ng-repeat="prdElement in palletElement track by $index&quo ...

Autocomplete is failing to provide any results

I am experiencing an issue with the autocomplete script as it is not displaying any names under the input field. Below is the code snippet from my index file: <head> <html lang="en"> <meta charset="utf-8"> <meta na ...

Animation showing on the progress bar is not correctly halted

I am encountering a problem with handling an animation of a progress bar in my code. The issue arises when I pause the animation, as it seems to slightly backtrack instead of pausing at the correct position upon clicking a button. Can someone help identify ...

AngularJS flexible route parameter

My AngularJS application has routes that can be either: www.website.com/blog/xyz www.website.com/blog/xyz/title/other-params In the second URL, the title parameter is used for readability purposes only and is not mandatory in the URL. Therefore, I have i ...

MaterialUI/Next.js digital clock selector

I am attempting to display a digital time picker or duration picker (minutes and seconds only) in my project theme, which utilizes material UI and Next.js. I have implemented the materialUI config for this but it always displays an analog clock instead of ...

The server is converting numeric JSON data types to strings

Currently, I am loading a CSV file, parsing it into a JSON object, and then converting the strings into numbers. Although these are displayed as numbers in the browser console, when I send the data to the server using AJAX, everything is interpreted as str ...

Error in Mathquill: Unable to access the 'prototype' property because it is undefined

I'm currently in the process of integrating MathQuill into a project I'm developing. After installing the package through NPM (npm install mathquill), I included the following <script> tags in the <head>: <script src="../node_ ...

I am looking to store individual objects in LocalStorage, however, I currently have the entire array saved

Struggling to figure out how to save a single object instead of the whole array when creating a movie watchlist. Clicking "add to watchlist" should save the single object in LocalStorage, while clicking "remove from watchlist" should remove it. I've a ...

Having trouble making SCSS mixins work with CSS variables in NextJS?

My current next.config.js setup looks like this: module.exports = (phase, {defaultConfig}) => { if ('sassOptions' in defaultConfig) { defaultConfig['sassOptions'] = { includePaths: ['./styles'], ...