Struggling to destructure props when using getStaticProps in NextJS?

I have been working on an app using Next JS and typescript. My goal is to fetch data from an api using getStaticProps, and then destructure the returned props. Unfortunately, I am facing some issues with de-structuring the props.

Below 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 am trying to pass projects and tools to my page like this.

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

export default Home;

However, when I attempt to do this, I encounter the following error.

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

Do I need to define an interface for the props? What could be causing this issue?

If I log props without de-structuring, it displays the expected arrays.

Thank you in advance for your help!

Answer №1

Explain the properties:

interface IHomepageProperties {
    projects: fillInThisBlank;
    tools: fillInThisBlank;
    children?: ReactNode; // import from react as required
}

const Homepage: NextPage = ({projects, tools}: IHomepageProperties) => {

Answer №2

One useful technique to consider is using pageProps within your page setup. Here's an example:

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

This method allows you to access the props retrieved from getStaticProps in your page.

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

Encountering a "No exported member" error while attempting to include & { session: Express.Session } in the MyContext type while following a tutorial on React, Express, and Typescript

Currently exploring a React, Express, and Typescript tutorial, which is still quite new to me. I am trying to grasp the concept of setting up custom types, and this is what I have so far. In my types.ts file: import { Request, Response } from "expres ...

Restrict the properties of an object to match the properties of a different object

I am currently developing an Object patching utility function with the following code snippet class Test{ a:number; b:number; } var c:Test={a:0,b:1} function patchable<T>(obj:T){ return { patch:function<K>(prop:K){ return patc ...

Retrieving POST data from requests in Node.js

My goal is to extract parameters from a POST request and store them in the variable postData using the request module. I found helpful information on handling post requests with Express.js here. Additionally, I came across this useful thread on how to retr ...

When using Python Selenium, we can see JavaScript in the view page source, but inspecting elements reveals the

I'm currently facing a challenge in accessing links to attachments for a web automation project. The issue lies in the fact that while I can view the HTML Code (divs and tables) when loading the webpage via Chrome and inspecting element, all I see in ...

Updating file extension name in ReactJS: A quick guide

Looking to modify a file name and extension within the react.js public folder. Changing index.html to index.php https://i.stack.imgur.com/zp1Ga.jpg ** ...

react.js function that returns 'undefined'

Having trouble with my class function that returns undefined when I try to use the return value. Main.js: let db = new Database() let username = db.get() return( //returns undefined <p>{username}</p> ) database.js: class Database { [... ...

What steps should be taken to ensure the Next.js "dev" server is secure enough for a production environment?

Our team's main objective is to convert a CMS-driven site into static HTML by "snapshotting" it. This process is easily achievable using getStaticProps and next export. However, we also require an intranet version that always fetches the latest conte ...

Merging the outcomes of a JSON call

Presently, I have an async function that returns a JSON response in the form of an array containing two objects. Please refer to the screenshot. How can I merge these objects to obtain: [{resultCount: 100, results: Array(100)}] I attempted the followin ...

Utilizing a third-party API within the next/api endpoint

I've recently started working with NEXTJS and developed a weather application. I'm integrating the openweather API, but I'm unsure how to use it within the next/api. I attempted creating a file named today.js inside the next/api directory an ...

What is the process for transferring information from a Ruby controller to an application JavaScript using AJAX?

When clicking a button, an AJAX call is made in my application.js file. It sends 3 data points to the events_controller#check action: //application.js $(document).on('click', "#check-button", function(){ ... $.ajax({ ...

Error: The variable 'err' is not declared in this scope.at line app.post

Tools I am Using Windows 10 Firebase (Firestore) Postman JavaScript, Express I'm learning from this video(https://www.youtube.com/watch?v=-vo7cu0xP4I) Situation Description I attempted to make a post request using Postman for testing purposes, b ...

The DOM element fails to load when utilizing the ng-view attribute

Recently, I have started working with AngularJS for my first web application and everything is running smoothly. However, I am now looking to integrate some charts using jQuery. The issue arises when trying to load a chart upon clicking on a menu item in ...

The issue that arises is that only the initial button is able to successfully trigger the opening of

My goal is to create a forum where users can reply to posts by clicking on a "Reply" button that triggers a Bootstrap modal. However, I am facing an issue where the modal only opens when clicking on the first button in a row due to it being placed within a ...

Using dynamic values in Angular functions

Here is the code snippet I am working with: $scope.testByValue = function() { $scope.fChanged($scope.lists.title); }; But I am facing an issue on the page where the value for: $scope.testValue = testValue; The variable testValue is being assigned a ...

Tips for implementing lazy loading for a section of a template in Angular 2

I have an Angular 2 component that has several sub-components within it. Some of these sub-components are expensive to load and may not always be necessary, especially if the user doesn't scroll far enough down the page. Although I am familiar with l ...

I'm struggling to figure out the age calculation in my Angular 2 code. Every time I try to run it,

Can anyone assist me with calculating age from a given date in Angular? I have written the following code but I keep getting undefined in the expected field. This is Component 1 import { Component, OnInit, Input } from '@angular/core'; ...

The locale is overridden by the server-side redirection in Next.js

On some of the pages in my website, I am utilizing getServerSideProps to make API calls and redirect users when necessary. Since the web application I'm developing is multilingual, it's crucial to always display content in the correct language fo ...

405 error: NGINX blocking POST method in Django DRF Vue.js application

I have encountered a strange issue while building my ecommerce site. Everything seems to be working fine, except for the forms. When attempting to post content, I keep receiving a 405 method get not allowed error. It's confusing as I am trying to use ...

Animating jQuery Counter with Changing Background Color

I've implemented a Counter that counts from 0 to a specified number, and it seems to be working perfectly. However, I want to add an animation where the background color of a div height animates upwards corresponding to the percentage of the counter. ...

What is the option for receiving automatic suggestions while formatting components in a react.js file?

When styling elements in our app using app.css or styles.css, VS Code provides auto-suggestions. For example, if we type just "back" for background color, it will suggest completions. However, this feature does not work in react.js or index.js. Why is that ...