Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

TypeScript+NextJS destructuring

I have object from postgresql:

enter image description here

Need to get id, name and content on NextJS component like that:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

export async function getServerSideProps() {
  const data = await prisma.note.findFirst()
  return {
    props: {
      userNote: data,
    },
  }
}
interface INote {
  id: number
  name: string
  content: string
}

const Home = ({ name, content, id }: INote) => {
  console.log(name)
  return <div>hello world</div>
}

but i got undefined. What’s wrong?

>Solution :

The problem is that your props in the Home component are not

{
  id: number
  name: string
  content: string
}

but actually,

{
 userNote: {
  id: number
  name: string
  content: string
 }
}

You’ll either need to change your destructuring and the type:

const Home = ({ userNote: { name, content, id } }: { userNote: INote }) => {

or you could change your getServerSideProps:

export async function getServerSideProps() {
  const data = await prisma.note.findFirst()
  return {
    props: data,
  }
}

In my experience it’s more idiomatic to go with the first approach and change it to:

export async function getServerSideProps() {
  const data = { id: 1, name: 'test', content: 'content' }
  return {
    props: {
      userNote: data,
    },
  }
}

interface INote {
  id: number
  name: string
  content: string
}

interface HomeProps {
   userNote: INote
}

const Home = ({ userNote: { name, content, id } }: HomeProps) => {
  console.log(name)
  return <div>hello world</div>
}

export default Home

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading