|
| 1 | +import Error from 'next/error' |
| 2 | +import Link from 'next/link' |
| 3 | + |
| 4 | +const CatchAllShow = ({ errorCode, show, slug }) => { |
| 5 | + |
| 6 | + // If show was not found, render 404 page |
| 7 | + if (errorCode) { |
| 8 | + return <Error statusCode={errorCode} /> |
| 9 | + } |
| 10 | + |
| 11 | + // Otherwise, render the page |
| 12 | + return ( |
| 13 | + <> |
| 14 | + <h1>getInitialProps: with catch-all routing</h1> |
| 15 | + <p> |
| 16 | + This page uses getInitialProps() to fetch a TV show from an API.<br/> |
| 17 | + It uses catch-all routing. |
| 18 | + </p> |
| 19 | + <p> |
| 20 | + URL parameters are made available in getInitialProps: |
| 21 | + <br/> |
| 22 | + {slug.map((item, index) => ( |
| 23 | + <span key={index}> |
| 24 | + [{index}]: {item}<br/> |
| 25 | + </span> |
| 26 | + ))} |
| 27 | + </p> |
| 28 | + <p> |
| 29 | + The first URL parameter determines the ID of the TV show to fetch. |
| 30 | + </p> |
| 31 | + <p> |
| 32 | + You can change the URL to anything else, such as /getInitialProps/1871/whatever/path/you/want. Try it! |
| 33 | + </p> |
| 34 | + <a |
| 35 | + href="https://github.com/FinnWoelm/next-on-netlify-demo/tree/master/pages/getInitialProps/[...slug].js" |
| 36 | + target="_blank"> |
| 37 | + View code on GitHub |
| 38 | + </a> |
| 39 | + |
| 40 | + <hr/> |
| 41 | + |
| 42 | + <h2>Show #{show.id}: {show.name}</h2> |
| 43 | + <a |
| 44 | + href={`https://api.tvmaze.com/shows/${show.id}`} |
| 45 | + target='_blank'> |
| 46 | + https://api.tvmaze.com/shows/{show.id} |
| 47 | + </a> |
| 48 | + |
| 49 | + <p> |
| 50 | + Type: {show.type} <br/> |
| 51 | + Language: {show.language} <br/> |
| 52 | + Status: {show.status} <br/> |
| 53 | + Premiered: {show.premiered} <br/> |
| 54 | + Official Site: {show.officialSite} <br/> |
| 55 | + Rating (average): {show.rating?.average} |
| 56 | + </p> |
| 57 | + |
| 58 | + <hr/> |
| 59 | + |
| 60 | + <Link href="/"> |
| 61 | + <a>Go back home</a> |
| 62 | + </Link> |
| 63 | + </> |
| 64 | + ) |
| 65 | +} |
| 66 | + |
| 67 | +CatchAllShow.getInitialProps = async ({ query }) => { |
| 68 | + // Get the ID to render |
| 69 | + const { slug } = query |
| 70 | + const id = slug[0] |
| 71 | + |
| 72 | + // Get the show |
| 73 | + const res = await fetch(`https://api.tvmaze.com/shows/${id}`); |
| 74 | + const show = await res.json(); |
| 75 | + |
| 76 | + // Set error code if show could not be found |
| 77 | + const errorCode = res.status > 200 ? res.status : false |
| 78 | + |
| 79 | + return { errorCode, show, slug } |
| 80 | +} |
| 81 | + |
| 82 | +export default CatchAllShow |
0 commit comments