Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

NextJS How do I use the id from a list of objects and redirect to a page based on that?

this might be a difficult nut to crack and I’m not sure if what I’m doing is correct.

So I have a list of movies that I get with an API fetch. Each movie object contains an id, title, run time, etc.

What I want to do is to map users each favorite movie with their names and use the movie names as links that will send the user to a page with more info about that movie. And I want the route to be the movie’s id.
So for example if I click on The Lion King (which has the id of 1) the address bar will say /movies?movieId=1

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The code that I have tried looks like this:

import { useRouter } from "next/router";
import { useState } from "react";

export const getServerSideProps = async (context) => {
  const { id } = context.query;

  const res = await fetch(`${process.env.BACKEND_URL}/User/${id}`);
  const data = await res.json();

  const res2 = await fetch(`${process.env.BACKEND_URL}/User/${id}/movies`);
  const data2 = await res2.json();

  return {
    props: { user: data, movies: data2},
  };
}

function Page({ user, movies }) {
  const router = useRouter();
  const [selectedMovie, setSelectedMovie] = useState();

  return(
    <div className={styles.movies}>
        {movies.map((item)=>{
          <Link key={item.movieId} value={item.movieId} onClick={(event) =>
            setSelectedMovie(event.target.value)}
            href={`/movies?movieId=${selectedMovie}`}>
              <a>{item.movie.name}</a>
          </Link>
    </div>
  );
}

I’ve come quite close I think but also I feel very lost. The address bar says /movies?movieId=undefined at the moment. Any help is highly appreciated. Also, I’ve tried searching for answers but I haven’t found anything that could help me. If any similar problems have been solved I would very much like to see them.

Thank you!

>Solution :

Just directly use item.movieId in the href.

<Link key={item.movieId} href={`/movies?movieId=${item.movieId}`}>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading