'How to get url in getstaticpath nextjs
I have face trubble to get url in getStaticPath
export const getStaticPaths = async (props) => {
if (url === 'blah') {
return {
paths: [
{ params: { pid: "create" } },
],
fallback: true,
};
}
Solution 1:[1]
you have to use getStaticProps() if you just to get a params
// pages/posts/[id].js
function Post({ post }) {
// Render post...
}
// This function gets called at build time
export async function getStaticPaths() {
// Call an external API endpoint to get posts
const res = await fetch('https://.../posts')
const posts = await res.json()
// Get the paths we want to pre-render based on posts
const paths = posts.map((post) => ({
params: { id: post.id },
}))
// We'll pre-render only these paths at build time.
// { fallback: false } means other routes should 404.
return { paths, fallback: false }
}
// This also gets called at build time
export async function getStaticProps({ params }) {
// params contains the post `id`.
// If the route is like /posts/1, then params.id is 1
const res = await fetch(`https://.../posts/${params.id}`)
const post = await res.json()
// Pass post data to the page via props
return { props: { post } }
}
export default Post
but if you want to get path as well you can use:
import { useRouter } from 'next/router'
//inside of your component
const { asPath } = useRouter()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
