How can I utilize the unique identifier from a list of objects in NextJS to dynamically redirect to a corresponding page?

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!

Answer №1

If you want to create a link using React, you can simply use item.movieId in the href attribute.

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to ensure webpacker compiled javascript only runs once the page has finished loading in a rails application

What is the best location to place window.onload for it to execute on every page within a Rails 6 application? ...

Modify the button's border color upon click action

I am looking to implement a feature where the border of a button changes when clicked once and reverts back when clicked again. This should apply individually to each of the 16 buttons with the same class. Additionally, I want to enable the ability to clic ...

Exploring React hooks: using setter function in cleanup process

My goal is to gain a deeper understanding of the React hooks life cycle, particularly focusing on minimizing re-rendering. To start off, I decided to create a simple component that displays the current time. The initial code snippet below functions perfect ...

Testing NestJS Global ModulesExplore how to efficiently use NestJS global

Is it possible to seamlessly include all @Global modules into a TestModule without the need to manually import them like in the main application? Until now, I've had to remember to add each global module to the list of imports for my test: await Tes ...

Tips for storing a JavaScript variable or logging it to a file

Currently working with node, I have a script that requests data from an API and formats it into JSON required for dynamo. Each day generates around 23000 records which I am trying to save on my hard drive. Could someone advise me on how to save the conte ...

What is the best way to conceal a dropdown menu when the page first loads?

I have a dropdown menu that is displaying like this: <ul> <li class="dropdown open"> <a aria-expanded="true" href="#" class="dropdown-toggle waves-effect waves-button waves-classic" data-toggle="dropdown"> <spa ...

Using Material-UI in a project without the need for create-react-app

My objective is to utilize Material-UI without relying on create-react-app, as I feel that it abstracts too much and hinders my learning process. Unfortunately, all the instructions I have come across are centered around create-react-app. I am aiming to s ...

Creating a Universally Unique Identifier in NextJs

I'm currently experimenting with the following code snippet: import { randomUUID } from 'crypto' var id = randomUUID() within my NextJs application, but unfortunately, I encountered the following error: index.js?46cb:369 Uncaught TypeErro ...

Troubleshooting a navigation issue in Angular involving the mat-sidenav element of material UI while transitioning between components

I would greatly appreciate your assistance in resolving the issue I am facing. I have been trying to navigate from one view to another, but when I use an <a> tag nested within a <mat-sidenav>, I encounter the following error: "Uncaught (in prom ...

Aligning the 'container-fluid' slideshow and video player

I'm struggling to center a video in a slick slider that is set as a 'container-fluid'. The slideshow and video display fine across the full width of the browser, but when I resize the browser window or view the site on a lower resolution, I ...

What is the best way to transform an array of objects into MenuItems for a Material-UI Select component?

I am facing an issue with mapping the values of field choices to create options for an MUI Select field from an array called fieldChoices. Here is how I populate the fieldChoices array: fieldChoices = { choices: filtered_status.map(function (item) { ...

Repeating rendering of component with reselect functionality

By utilizing the selectManageAdvancedUserFilters selector, my component is re-rendering twice. However, without this selector, it only renders once. export const selectManageAdvancedUserFilters = typeCode => { return createSelector([selectUserFilters ...

Issue with NextJS Image Optimization in Vercel's production environment

As of now, I am developing a NextJS application that will eventually be deployed with multiple domains on Vercel. One of the key features of my application is the dynamic rendering of images. While all images display correctly in the preview environment on ...

Troubleshooting navigation problems in AngularJS Bootstrap Navbar

Currently, I am working on integrating AngularJS with Bootstrap3 for a mobile application. In my index.html file, I have added a navbar (navbar-fixed-top) and there are forms loaded through partials/myform.html. However, when I scroll the page and a textbo ...

If the input is marked as checked, apply a class to the corresponding HTML element

I need to manipulate the .form-group class by adding it if the nearest hotelObj element is checked, and removing it when hotelObj is unchecked. Instead of using addClass(), I prefer to utilize css(). $(".form-group").click(function() { if ($(this).ch ...

Place background image in the center with a background color overlay

After browsing through this post on Stack Overflow, I managed to stretch my background image using CSS with the background-size: cover; property. However, I realized that this solution doesn't completely meet my needs. I'm dealing with an image ...

Combining and removing identical values in JavaScript

I need to sum the price values for duplicated elements in an array. Here is the current array: var products = [["product_1", 6, "hamburger"],["product_2", 10, "cola"],["product_2", 7, "cola"], ["product1", 4, "hamburger"]] This is what I am aiming for: ...

A little brain teaser for you: Why is this not functioning properly on Google Chrome?

Have you noticed that the code below works perfectly in Firefox, but fails in Chrome when trying to 'post' data? $("a").click(function() { $.post("ajax/update_count.php", {site: 'http://mysite.com'}); }); Hint: Make sure you are us ...

Managing Dependencies in Redux: Ensuring Proper Updates for Interconnected Resources

Let's say I have a redux state structure like this: { user: null, purchases: [], } The purchases are associated with a user, so whenever the user is updated, I also want to update the purchases (although there may be other times when purchases n ...

Is there a way to split the text into distinct pages within a contenteditable area, similar to the functionality in Google Docs

I've been working on developing a specialized browser-based text editor and I've encountered a puzzling question. How can I detect and split long texts into separate pages, similar to how Google Docs handles pagination? I'm aware that Google ...