This task seems challenging and I'm unsure if my approach is correct.
I have a collection of movies retrieved through an API fetch. Each movie object includes details like an id, title, and duration.
My goal is to associate each user's favorite movie with their name and create links using the movie titles. These links will direct the user to a page with more information about the selected movie, using the movie's id as part of the route. For instance, clicking on "The Lion King" (with id 1) should show /movies?movieId=1 in the address bar.
Here is the code I've attempted:
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 feel like I've made progress, but I'm struggling with the address bar displaying /movies?movieId=undefined currently. Any assistance would be greatly appreciated. I've searched for solutions but haven't found any that apply to my situation. If similar issues have been resolved before, I would love to learn from them.
Thank you!