ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [NextJS] getStaticPaths
    Programming/JavaScript & TypeScript 2022. 9. 7. 10:02
    728x90

    Dynamic Router 사용중에는 getStaticPaths가 필요하다.

     

    getStaticPaths는 빌드시에 static하게 페이지를 생성한다. 

    */photos/[id]/index.tsx 에서 id값에 따라서 dynamic하게 페이지를 생성한다.

    즉, id값이 바뀜에 따라서 내부에서 가져오는 api의 값도 달라진다.

     

    getStaticPaths에서 params에 넘긴 정보는 getStaticProps에서 context.params안에 들어 있는데, 

    지금 문제가 이걸 꺼낼때 오류가 발생한다..왜냐하면 context는 ParsedUrlQuery type인데 이 안에 

    우리가 getStaticPaths에서 넣어준 type이 없다..

     

    그래서 ParsedUrlQuery를 확장해서 우리가 넣어준 타입을 넣고,interface를 새로 만들어야 한다.

    interface IParams extends ParsedUrlQuery {
        id:string
    }

    그리고 이걸 가져다 쓰면 된다. 

    import Image from 'next/image'
    import {Photo} from "../../content";
    import Link from 'next/link'
    import {useRouter} from "next/router";
    import {GetStaticPaths, GetStaticProps, InferGetStaticPropsType} from "next";
    import {ParsedUrlQuery} from "querystring";
    
    const Index = ({photo}:InferGetStaticPropsType<GetStaticProps>) => {
        //페이지가 열릴때 어떤 정보가 오는지 볼 수 있다.
        //주소가 바뀔 때마다 정보도 바뀐다.
        // const router = useRouter()
        // console.log(router)
    
        const {title, id, url} = photo
        return (
            <div>
                <h2>Image {title}</h2>
                <Image src={url} width={500} height={500}/>
    
                <Link href='/content'><a>Back To Photos</a></Link>
            </div>
        )
    }
    
    interface IParams extends ParsedUrlQuery {
        id:string
    }
    export const getStaticProps:GetStaticProps = async (context) => {
        //페이지가 열릴때 id값 받아와서 그것의 정보만 가져오게
        //근데 이렇게 하면 에러남...photos/[id].tsx 즉 dynamic SSG page는 static path value가 필요함 (getStaticPath
    
        //context.params안에 getStaticPaths에서 넘겨준 id가 들어있음
        const {id} = context.params as IParams
        const res = await fetch(`https://jsonplaceholder.typicode.com/photos/${id}`)
        const photo = await res.json()
    
        return {
            //{posts:posts}나 posts를 하나만 써도 됨....
            props:{photo}
        }
    }
    
    export const getStaticPaths = async () => {
        //근데 동적 생성이라고 하면서 id:'1'이면 동적생성이 아니지 않나...
        //
        // return {
        //     paths:[
        //         {
        //             params:{id:'1'},
        //         },
        //         {
        //             params:{id:'2'},
        //         },
        //     ], fallback:false
        // }
    
    
        //전체를 받아와서 id만 뽑아온다.
        //동적으로 만들자...
    
        const res = await fetch('https://jsonplaceholder.typicode.com/photos?_start=0&_end=10')
        const photos = await res.json()
    
        const ids = photos.map((photo: { id: number; })=>photo.id)
        const paths = ids.map((id:number) =>{
            return {
                params:{id:id.toString()}
            }
        })
    
        return {
            paths:paths,
            fallback:false
    
        }
    
    }
    export default Index

     

    페이지가 열릴때 정보는 'useRouter'를 이용해서 보면 된다. 

    import {useRouter} from "next/router";
    
    const router = useRouter()
    //페이지가 열릴때 어떤 정보가 오는지 볼 수 있다.
    //주소가 바뀔 때마다 정보도 바뀐다.
    console.log(router)

     

    출처 

    https://wallis.dev/blog/nextjs-getstaticprops-and-getstaticpaths-with-typescript

Designed by Tistory.