The implementation of getStaticPaths was done independently of getStaticProps - TypeScript

I am currently in the process of setting up a new blog using a combination of nextJS, TypeScript, and sanity CMS. The homepage is already set up to display posts perfectly. Next on my list is to display the details of each post when it is clicked, based on its individual slug. So far, I have been able to successfully fetch the data for the blog posts by calling the query inside the sanity dashboard.

https://i.stack.imgur.com/rissA.png

Here are the Post typings:

export interface Post {
  _id: string
  _createdAt: string
  title: string
  author: {
    name: string
    image: string
  }
  description: string
  mainImage: {
    asset: {
      url: string
    }
  }
  slug: {
    current: string
  }
  body: [object]
}

[slug].tsx:

import { GetStaticProps } from 'next'
import Header from '../../components/Header'
import { sanityClient, urlFor } from '../../sanity'
import { Post } from '../../typings'

interface Props {
  post: Post
}
function Post({ post }: Props) {
  //   console.log(post)
  return (
    <main>
      <Header />
      {/* <img src={urlFor(post.mainImage).url()} alt="" /> */}
    </main>
  )
}

export default Post
export const getStaticPaths = async () => {
  const query = `*[_type == "post"]{
        _id,
        slug{
            current
        }
    }`
  const posts = await sanityClient.fetch(query)
  const paths = posts.map((post: Post) => ({
    params: {
      slug: post.slug.current,
    },
  }))

  return {
    paths,
    fallback: 'blocking',
  }
}
export const GetStaticProps: GetStaticProps = async ({ params }) => {
  const query = `*[_type == "post" && slug.current == $slug][0]{
  _id,
  _createdAt,
  title,
  author-> {
  name,
  image
},
 description,
 mainImage,
 slug,
 body
}`
  const post = await sanityClient.fetch(query, {
    slug: params?.slug,
  })

  if (!post) {
    return {
      notFound: true,
    }
  }
  return {
    props: {
      post,
    },
    revalidate: 60,
  }
}

I encountered the following error:

Error: getStaticPaths was added without a getStaticProps in /post/[slug]. 
Without getStaticProps, getStaticPaths does nothing

Answer №1

The issue lies in your incorrect definition of getStaticProps. It appears that you have mistakenly capitalized the first letter, making it GetStaticProps instead of getStaticProps which is the correct function for Next.js' life cycle.

To resolve this, simply update it to getStaticProps: GetStaticProps

export const getStaticProps: GetStaticProps = async ({ params }) => {
  const query = `*[_type == "post" && slug.current == $slug][0]{
  _id,
  _createdAt,
  title,
  author-> {
  name,
  image
},
 description,
 mainImage,
 slug,
 body
}`
  const post = await sanityClient.fetch(query, {
    slug: params?.slug,
  })

  if (!post) {
    return {
      notFound: true,
    }
  }
  return {
    props: {
      post,
    },
    revalidate: 60,
  }
}

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

How do I use TypeScript and protractor to retrieve the column index of a grid by matching the header text of that column?

I have been attempting to create a function that can determine the column index of a grid based on the header text for that particular column. Despite several attempts, as shown in the comments below, the function consistently returns -1 instead of the exp ...

Tips for effectively passing an array to props in Vue when leveraging Typescript and the class component decorator

I'm currently struggling to understand the proper method of passing an array as a prop to a component in Vue, using Typescript and the class component library. Following the official template, I attempted the following approach: <script lang="ts"& ...

Exploring the synergies between Angular 5 and atmosphere.js

I've been trying to incorporate atmosphere.js into my angular 5 project. So far, I've followed these steps: npm install --save @types/atmosphere.js npm install --save atmosphere.js In addition, I have set up a service as shown below: import { ...

Using the useRef hook in a TypeScript project to retrieve a boolean value

As I work on developing an application using Nextjs, I have encountered an issue while using react useRef with typescript. The problem arises when I use useRef without typescript, everything works smoothly. However, the moment I include HTMLDivEleement as ...

What are the steps to properly set up an external image loader in next.js?

I'm currently leveraging next.js export to generate a static html export that is housed on google cloud storage. To achieve this, I have incorporated a workaround in my next.js configuration file. images: { loader: 'imgix', path: 'ht ...

The presence of a method is triggering an Error TS2741 message stating that the property is missing in type

Here is a simplified code snippet that highlights the issue I am facing: class Test { prop1 : boolean prop2 : string method() { } static create(prop1 : boolean, prop2 : string) : Test { let item : Test = { prop1: prop1, prop2: pro ...

The utility of commander.js demonstrated in a straightforward example: utilizing a single file argument

Many developers rely on the commander npm package for command-line parsing. I am considering using it as well due to its advanced functionality, such as commands, help, and option flags. For my initial program version, I only require commander to parse ar ...

Error-throwing constructor unit test

In my code, I have implemented a constructor that takes in a configuration object. Within this constructor, I perform validations on the object. If the validation fails, I aim to throw an error that clearly describes the issue to the user. Now, I am wonde ...

Passing an event from onSubmit in React without using lambdas

Within our current project, the tslint rule jsx-no-lambda is in place. When attempting to capture event from onSubmit, this is how I typically write my code: public handleLogin = (event: React.FormEvent<HTMLFormElement>) => { event.preventDe ...

bundle.js encountered a TypeError when attempting to read a property that was undefined, specifically while trying to access the PriceIndexationDataControlStandard

In the midst of developing a React component using the Microsoft PCF Framework, I encountered a perplexing error seemingly out of the blue. While making changes in TypeScript without even executing any build commands, the rendering of my component suddenly ...

Having trouble connecting to the database server on `postgres` port `5432` using an AWS-RDS URL

Tools in my arsenal: nextJS; prisma; postgresql; docker; I've been attempting to establish a connection with the database by using this URL: DATABASE_URL="postgresql://USER:PASSWORD@HOST:5432" The database in question is an AWS RDS Postgr ...

What exactly occurs when a "variable is declared but its value is never read" situation arises?

I encountered the same warning multiple times while implementing this particular pattern. function test() { let value: number = 0 // The warning occurs at this line: value is declared but its value is never read value = 2 return false } My curi ...

Could it be possible for a Firestore onUpdate trigger's change parameter, specifically change.after.data() and change.before.data(), to become null or undefined?

Presented below is a snippet of my cloud function exports.onUpdateEvent = functions.firestore.document('collection/{documentId}') .onUpdate((change, context) => { const after: FirebaseFirestore.DocumentData = change.after.data(); const ...

When using this.$refs in Vue, be mindful that the object may be undefined

After switching to TypeScript, I encountered errors in some of my code related to: Object is possibly 'undefined' The version of TypeScript being used is 3.2.1 Below is the problematic code snippet: this.$refs[`stud-copy-${index}`][0].innerHTM ...

TypeError: Unable to find TextEncoder in mongoose and jest when using TypeScript

Currently, I am working on a project using Node 14 along with Express v4.16.3 and Typescript (v4.7.4). Recently, I added Mongoose (v6.5.2) to the project, and while the logic code seems fine, most of the tests executed by Jest (v26.4.2) are failing with th ...

The cookie value is blank once after moving to the second page

I'm facing an issue with 2 domains where performing an action on the first domain results in setting a cookie that should be accessible on both domains. However, when trying to read the value of this cookie on the second domain, it appears empty. Can ...

The issue arises when attempting to utilize getStaticProps to retrieve data from a Laravel API, resulting in the error message: "connect ECONNREFUSED ::

In my setup, I have organized my project into two main folders: the backend for Laravel API and the frontend for Next.js https://i.stack.imgur.com/QZcZ2.png Within my project structure, I have a configured axios file located in /lib/axios.ts https://i.st ...

Testbed: Issue encountered: Unable to resolve all parameters for PriDateInput component

I am facing an issue while creating an Angular Component with the help of TestBed. The error message I receive is as follows: Error: Can't resolve all parameters for PriDateInput: (?). error properties: Object({ ngSyntaxError: true }) ...

Are there any more efficient methods to retrieve an object from an arrow function in TypeScript?

Trying to retrieve an object from an arrow function is posing a challenge for me, especially with the following function f: myMethod(f: data => { return { someField: data.something }; }); I am aware that for simple types, you can condense the arrow ...

Pagination problem arises when sorting through items

I am facing an issue with filtering items on different pages of my React website. The problem I encounter is that the filtering functionality only works on the initial page where the data is loaded. Code: CustomersEpolicyPage.tsx import React, {useEffect ...