skip to Main Content

I’m probably doing something wrong but I’m following the official doc.
I want this component to be static and for me to be able to call it on any page, but as it is, it needs a parameter and I don’t want to pass this parameter on the page where I’m calling the component. Is there a way to do it?

component:

import { GetStaticProps, InferGetServerSidePropsType } from "next"

type PersonalitiesProps = {
  id: string,
  name: string,
  historia: string
}

export const getStaticProps = (async (contexte) => {
  const res = await fetch('http://localhost:8000/api/v1/personalidades', {
    method: "GET",
  })
  const data = await res.json()
  return { props: { data } }
}) satisfies GetStaticProps<{
  data: PersonalitiesProps
}>

const Personalities = (data: InferGetServerSidePropsType<typeof getStaticProps>) => {
  return data
}

export default Personalities

app/pages.tsx:

import Personalities from '@/components/Personalities'

export default function Home() {
  return (
    <section>
      <h1>Hello, Word!</h1>
      <Personalities />
    </section>
  )
}

errors:

Property ‘data’ is missing in type ‘{}’ but required in type ‘{ data: any; }’.ts(2741)
index.tsx(14, 21): ‘data’ is declared here.

Error: Objects are not valid as a React child (found: object with keys {}). If you meant to render a collection of children, use an array instead.

I’m following the steps in this documentation, even though my project is nextjs ^14.0 and it’s APP ROUTE:

https://nextjs.org/docs/pages/building-your-application/data-fetching/get-static-props

2

Answers


  1. you have to make the prop data optional, by using ‘?’ afer it’s declaration.

    const Personalities = (data?: InferGetServerSidePropsType<typeof getStaticProps>) => {
      return data
    }
    

    now you can use the componente using or not the prop data.

    Login or Signup to reply.
  2. No offense but your code is ruining next.js

    • getStaticProps is called only at pages, at build time. I dont understand how you are getting this error:

    Error: Objects are not valid as a React child (found: object with keys
    {}). If you meant to render a collection of children, use an array
    instead.

    because Personalities should be returning undefined, since getStaticProps will never get called automatically in components.

    • getStaticProps are removed after next.js 13.
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search