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

What is the process for creating a unit test case for an Angular service page?

How can I create test cases for the service page using Jasmine? I attempted to write unit tests for the following function. service.page.ts get(): Observable<Array<modelsample>> { const endpoint = "URL" ; return ...

Error: The specified property is not found in type 'never' - occurring with the ngFor loop variable

When working with API responses and dynamically sorting my view, I utilize an ngFor loop. Here's the snippet of code in question: <agm-marker *ngFor="let httpResponses of response" [latitude]= "httpResponses.lat" [longitude]=& ...

Unable to showcase Pyodide results in a textarea field

I'm facing difficulties when it comes to displaying Python output from pyodide on a textarea named 'output'. I am working with react/next.js and my objective is to have the python output appear in the textarea as soon as the page loads. Howe ...

Unusual actions observed in Ionic 3 app using webview 3 plugin

I am currently facing a significant problem with Webview 3. One of our developers upgraded it to webview 3 without utilizing the Ionic native webview plugin, and surprisingly, it is functioning well on our Ionic 3 application. As per the documentation avai ...

Module not found

Hey everyone, I recently updated my project to node version v14.18.0, but now I'm encountering a "module not found" issue (see screenshot below). Any suggestions on how to resolve this? https://i.stack.imgur.com/k0u82.png ...

Exploring hover-effects in Next JS

I am currently facing a challenge while trying to utilize the npm package hover-effect within a functional component. Despite my previous experience with similar packages in create-react-app, I am relatively new to next.js. Below is an example of how the p ...

Ways to access component load status in Next.js

I'm currently developing a basic Pokedex to showcase all Pokemon. I am utilizing a map function on an array of Pokemon objects to display all the cards in this manner: {pokemons.results.map((el, i) => { return ( <di ...

Testing the functionality of functions through unit testing with method decorators using mocha and sinon

I have a class method that looks like this: export class MyClass { @myDecorator() public async createItem(itemId: string, itemOptions: ItemOption[]): Promise<boolean> { // ... // return await create I ...

A problem arises when using the visibility:hidden property with the useEffect hook in Next JS

Having trouble with the CSS property visibility: hidden; in combination with useEffect. I created a basic component containing two divs, each with text. My goal is to split the letters and wrap them in individual span elements. This function works as expec ...

Solving the issue of interconnected promises in Angular services

I am utilizing a DynamoDB service within my Angular project which returns a promise through a series of promises. This process involves retrieving a subId from Cognito and then passing that subId to a DynamoDB get query: async getUserObject(): Promise< ...

Deployment of a NextJS14 app to Vercel encountered an issue: Unexpected token '<' found in JSON at position 0

Here is the issue at hand: next: 14.1.4 next-auth: 4.24.7 node version: 20 This is the structure of my authentication folder: No errors occur when running npm run dev I've been investigating this issue for three days, but I am still stuck. I belie ...

What is the best way to eliminate query parameters in NextJS?

My URL is too long with multiple queries, such as /projects/1/&category=Branding&title=Mobile+App&about=Lorem+ipsum+Lorem+. I just want to simplify it to /projects/1/mobile-app. I've been struggling to fix this for a week. While I found so ...

Is Operator Overloading supported in Typescript?

I'm curious about whether operator overloading is supported in typescript. If it does exist, I'd be happy to provide an example or a link for you to explore further. ...

How can I display the values stored in an array of objects in Angular 2

I need help printing out the value of id from an array that is structured like this: locations = [ {id: '1', lat: 51.5239935252832, lng: 5.137663903579778, content: 'Kids Jungalow (5p)'}, {id: '2', lat: 51.523 ...

I'm trying to determine in Stencil JS if a button has been clicked in a separate component within a different class. Can anyone assist

I've created a component named button.tsx, which contains a function that performs specific tasks when the button is clicked. The function this.saveSearch triggers the saveSearch() function. button.tsx {((this.test1) || this.selectedExistingId) && ...

originalRenderPage has not been declared

I encountered an issue while working on my new nextjs app. The problem arose when I tried to add a carousel using props in my project, resulting in an error stating that 'originalRenderPage' in Document.js is not defined. Any assistance would be ...

Categories for the Promise.all() function

I'm feeling lost trying to understand the differences between the request tuple return type and Promise.all(). This is driving me crazy. Any suggestions? const createPromises = async (utteranceObject: Array<string[]>): Promise<Array<[s ...

Tips for editing events in the "react-big-calendars" component

I am looking to implement a feature where users can click on events in a calendar and then edit either the dates or event titles. Can this functionality be achieved using "react-big-calendar"? If not, are there any other packages you can recommend? <Cal ...

Error occurred after attempting to make a GET request

What I aim to achieve: I need to send two parameters from the front-end to the back-end. This is the code snippet: In TypeScript file: activeFromActiveToQuery(req?: any): Observable<ResponseWrapper>{ const options = createRequestOption(req) ...

Retrieve data in Next JS once for display across all pages

I came across this page which provides some relevant information, but I still need more clarification. The issue I'm facing is with a generic component that showcases an appbar on my website. This appbar contains a user avatar retrieved from a separa ...