user16910522
user16910522

Reputation:

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

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!

Upvotes: 1

Views: 1375

Answers (1)

Unmitigated
Unmitigated

Reputation: 89412

Just directly use item.movieId in the href.

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

Upvotes: 1

Related Questions