Home > Blockchain >  Can't de-structure props from getStaticProps in NextJS?
Can't de-structure props from getStaticProps in NextJS?

Time:02-20

I am building an app with Next JS and typescript. I am trying to call data from an api with getStaticProps, and then de-structure the returned props. For some reason, I can't get the props to de-structure.

Here is my getStaticProps function.

export async function getStaticProps() {
  const projects = await client.fetch(groq`
  *[_type == "project"]{
    name, url, description, image, tools[]->{name,image}
  }`);

  const tools = await client.fetch(groq`*[_type == "techtool"]{
    name, featured, url, image
  }`);

  return {
    props: {
      projects,
      tools,
    },
  };
}

I then am trying to pass projects and tools to my page like so.

const Home: NextPage = ({projects, tools}) => {
  console.log(props);
  return (
    <React.Fragment>
      <Nav />
      <Intro />
      <Contact />
      <Sidebar />
      <Footer />
    </React.Fragment>
  );
};

export default Home;

However, I am getting the following error when I do this.

"Property 'projects' does not exist on type '{ children?: ReactNode; }'."
"Property 'tools' does not exist on type '{ children?: ReactNode; }'."

Do I need to somehow apply an interface to the props? What am I doing wrong?

If I log props to the console without de-structuring, it returns the two arrays it should.

Thanks in advance!

CodePudding user response:

Annotate the props:

interface IHomeProps {
    projects: whatGoesHere;
    tools: whatGoesHere;
    children?: ReactNode; // import from react if needed
}

const Home: NextPage = ({projects, tools}: IHomeProps) => {

CodePudding user response:

You should try use pageProps in your page like this:

const Home: NextPage = ({ pageProps: {projects, tools} }) => {
  console.log(projects, tools);
  return (
    <React.Fragment>
      <Nav />
      <Intro />
      <Contact />
      <Sidebar />
      <Footer />
    </React.Fragment>
  );
};

This is how you can get the props from getStaticProps in your page.

  • Related