0

I am new to working with typescript and next.js. I am using Vercel to deploy a Next.js webapp that will pull data from a heroku postgresSQL db using Prisma. I am trying to render some data on the page using observable/d3, using getStaticProps to fetch the data, then pass it to the Home page component.

export const getStaticProps: GetStaticProps = async () => {
    let data: Array<object> = await prisma.test.findMany()
    console.log(data)
    return { props: { data } }
}

const Home: NextPage = ( data ) => {
    console.log(data)
    useEffect(() => {
    document.body.append(
        Plot.barY(data, {x: "letter", y: "frequency"}).plot()
    )
 }, [])
 ...
}

The first console log in getStaticProps returns the data in my desired format, an array of objects:

[
 {letter: 'A', frequency: 0.0123}
 ...
 {letter: 'Z', frequency: 0.00234}
]

After passing the data to the Home component, data is wrapped in an object and looks like this:

 {
  data: [
   {letter: 'A', frequency: 0.0123}
   ...
   {letter: 'Z', frequency: 0.00234}
  ]
 }

My plotting function wants an array of objects, but after passing data using getStaticProps to the Home component, data gets 'wrapped' in those JS Curley braces and I don't want that. Can someone help me understand why and how to correct this behavior? Using typeof data in both console.log returns object

  • You should either destructure the props passed to the `Home` page component `({ data })`, or use `(prop)` and access the data with `props.data`. – juliomalves Nov 10 '21 at 20:00

1 Answers1

1

You should have been destructured the props Home({ data }) instead of Home(data)

import { InferGetStaticPropsType } from 'next'

type Test = {
  letter: string
  frequency: number
}

export const getStaticProps = async () => {
  let data: Test[] = await prisma.test.findMany()
  return {
    props: {
      data
    }
  }
}

// Destructure the props
const Home: NextPage = ({ data }: InferGetStaticPropsType<typeof getStaticProps>) => {
  // will resolve tests to type Test[]
}
nart
  • 1,508
  • 2
  • 11
  • 24
  • If I have a couple of objects inside the data object, does it make sense to send it together as a single `data` prop, or split it into several individual props? Consider that the component represents a page which consists of several subsections, each of which takes one key from the `data` object. – sayandcode Oct 07 '22 at 06:39
  • 1
    If its all data retrieve from single API call I would send a single object data, again whether you send individual or all in once you need to destructuring that props anyway. – nart Oct 07 '22 at 15:55
  • Yeah so if I have to destructure either way, is there any advantage to doing it via props? Like testing or something? – sayandcode Oct 07 '22 at 17:07