0

I would like to use the film title in my route URL (eg films/fletch), but the subsequent getServerSideProps request requires the episode_id.

How do I pass both film.episode_id and film.title to films/[id]/index.js?

Movies.js

<Link 
  href={{
    pathname: `/films/[id]`,
    query: {
      id: film.episode_id
    },
  }}
  as={`/films/${encodeURIComponent(film.title)}`} >
    <a>{film.title}</a>
</Link>
films/[id]/index.js

import {useRouter} from 'next/router'

const movie = () => {
    const router = useRouter();
    console.log(router);  
    const { id } = router.query

    return (
        <div>Movie page for <strong>{id}</strong></div>
    )
}
newcasio
  • 243
  • 1
  • 6
  • 14
  • Is the `Link` with `as` prop not achieving the desired behaviour? That should pass the `episode_id` correctly to the next page, while displaying the `title` in the address bar. – juliomalves Oct 03 '21 at 15:59
  • @juliomalves the title is appearing in the address bar as desired. But I do not know how to access the episode_id. – newcasio Oct 03 '21 at 19:43
  • If you're trying to access it from `getServerSideProps` then you can use `context.params.id`. See [How to access route parameter inside getServerSideProps in Next.js?](https://stackoverflow.com/a/69059032/1870780) for details. – juliomalves Oct 03 '21 at 21:03

1 Answers1

0

You can use context.query to get the query params of the link.

// films/[id]/index.js

import PropTypes from 'prop-types'

const Movie = ({ query }) => {
  return (
    <div>Movie page for <strong>{query.id}</strong></div>
  )
}

Movie.propTypes = {
  query: PropTypes.shape({
    id: PropTypes.string,
  })
}

export async function getServerSideProps(context) {
  return {
    props: { query: context.query }
  }
}

export default Movie