1

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!

turivishal
  • 34,368
  • 7
  • 36
  • 59
Oskar
  • 37
  • 5
  • 1
    Semi-unrelated QnA, but will explain why setting state and trying to read it the next line doesn't work in React: https://stackoverflow.com/questions/54069253/the-usestate-set-method-is-not-reflecting-a-change-immediately/54069332#54069332 TL;DR React state updates are not immediately processed. Just pass the movie id directly in the link target string like Unmitigated's [answer](/a/73706144/8690857) below. – Drew Reese Sep 13 '22 at 16:11

1 Answers1

2

Just directly use item.movieId in the href.

<Link key={item.movieId} href={`/movies?movieId=${item.movieId}`}>
Unmitigated
  • 76,500
  • 11
  • 62
  • 80