简体   繁体   中英

Next.js getStaticProps params in context equal '[object Object]' / getStaticProps gets called multiple times

I am trying to understand why getStaticProps is getting called multiple times.

The relevant file is called [postId].js in my pages/posts folder; code below:

const MyPost({post}) => {
// Main component in here
}

export default MyPost

export async function getStaticProps(context) {
    const { params } = context;
    console.log('params', params)
    // Call API with params.postId and get postContent
    return {
        props: {
            post: postContent,
        },
        revalidate: 10, // In seconds
    }
}

export async function getStaticPaths() {
    const res = await axios.get(API_URL + '/get-post-ids')
    // Get the paths we want to pre-render based on posts
    const paths = res.data.post_ids.map((id) => ({
        params: { postId: id },
    }))
    return { paths, fallback: 'blocking' }
}

This logs

params { postId: 'post-1' }
params { postId: '[object Object]' }

Why does getStaticProps get called twice? And why is the path parameter in the second render [object Object] ? Anything i can do to prevent that from happening?

I am trying to call an API with the path parameter and i can see the two requests on my backend, the first one works without an issue, but then the second one causes an error.

Thanks a lot!

EDIT:

Logging out paths in getStaticPaths I get

 paths [ { params: { postId: 'post-1' } }, { params: { postId: 'post-2' } } ]

so not sure where [object Object] comes from...

The getStaticProps function is getting called twice because getStaticPaths returns a fallback: 'blocking' option, which means that when a new page is visited that is not pre-rendered, Next.js will fallback to server-side rendering, and in this case it means that getStaticProps will be called again to render the new page.

Regarding the postId being [object Object] , it is likely that the object that is being passed as the postId parameter is not a string, but an object. It is possible that you are passing an object in the paths array that getStaticPaths returns. Ensure that the postId property of the object passed in the paths array is a string, or convert it to a string before passing it to getStaticPaths .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM