Obtain the content of a clicked item on the following page using NextJs

I am currently working on a nextjs app that displays a list of 10 movies on the homepage, each with a Button / Link that leads to a specific page for that movie where all its content is shown.

Initially, I tried adding the movie id to the Link like this:

  <Link href="/movies/[title]" as={`/movies/${movie._id}-${movie.title}`} prefetch>
    <IconButton aria-label="Open">
      <LaunchIcon />
    </IconButton>
  </Link>

However, I realized that trimming the id from the URL in the next page and making an additional API request for movie information was not the best practice.

In the single movie component movies/[title].tsx, I attempted to create a basic movie object:

const movieObj = {
  _id: 1,
  title: "",
  release_at: new Date(),
  created_at: new Date()
};

and used hooks to set the data:

const [movie, setMovie] = useState<IMovie>(movieObj);

I am now seeking a better solution in Next.js. Can you help me achieve this?

Answer №1

If you're looking to access URL slugs, make sure to refer to the Next.js documentation. The docs mention that you can utilize the useRouter hook for this purpose.

import { useRouter } from 'next/router';

const router = useRouter();    
const { title } = router.query;

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

Ways to fix the error "Response must contain an array at." when creating a dropdown menu

I encountered an error while trying to create a dropdown menu. I referred to the documentation available at The response must include an array at " . ". Although I came across some links with potential solutions, none of them seemed to work for me: https ...

Troubleshooting AngularJS Get Function Failure

New to the world of AngularJS, I find myself faced with a challenge. My .NET MVC WebAPI Restful app is up and running on an IIS server. However, when I attempt to query the API using , the response I receive is: [{"Id":1,"Name":"Glenn Block","Created":"00 ...

A guide on efficiently incorporating a php variable into json format, then transferring it to ajax

My Sample Code var ajaxResponse = xmlhttp.responseText; //ajax response from my php file jsonData = JSON.parse(ajaxResponse); alert(jsonData.result); And in my PHP Script $resultValue = 'Hello'; echo '{ "result":"' . $result ...

Angular does not seem to be triggering $watch for changes in arrays

Trying to activate a $watch function after a delay in Angular: Controller Information .controller('MyCtrl', ['$scope', function ($scope) { $scope.chickens = ["Jim", "Joe", "Fred"]; $scope.chickens.push("Steve"); setTimeou ...

encountering a glitch while using console.log(util.format

Let me start by saying that I am fairly new to working with node.js. A friend of mine assisted me in writing the code snippet below. I have successfully installed the necessary packages search-google-geocode, csv-parser, fs, util, and async using npm. H ...

Converting Callbacks to Promises in Node.js

I am facing a challenge with my node js application as I am attempting to promisify multiple callback functions without success. It has reached a point where I am unsure if it is even feasible. If you can assist me in promisifying the code provided below, ...

Managing the jQuery.noConflict function

Upon review, I noticed that the scripts I inherited start like this: var $j = jQuery.noConflict(); The purpose behind this code is not clear to me. While I understand the intent is to avoid conflicts, I am uncertain about the specific conflict it aims to ...

Is it possible that a declaration file for module 'material-ui/styles/MuiThemeProvider' is missing?

I have been trying to implement the react material-ui theme after installing it via npm. However, I am encountering errors when adding 'import MuiThemeProvider from "material-ui/styles/MuiThemeProvider";' in boot-client.tsx: TS7016: Could not ...

Automatically update button appearance upon reaching zero value using JavaScript

Whenever I click the button, the user's HP decreases until it reaches 0 and then the button changes. However, a peculiar issue arises when the userHealth hits zero - the button does not change immediately. An additional click is required for the butto ...

What is the process for creating a unit test case for a button's onClick event with Jest?

In my attempt to unit test the onClick event of a button in a component, I encountered some challenges. Specifically, I am unsure how to properly test the onClick event when it triggers a function like Add(value). App.js function App(){ const[value,set ...

jQuery does not provide the reference of a basic canvas element

I'm having trouble with a simple initialization function that is supposed to create a canvas element in the body and save its reference in a variable. No matter what I try, jQuery doesn't seem to want to return the reference. I attempted refere ...

How can JavaScript be utilized to disable the use of the spacebar?

I have implemented a live search feature on the website I'm working on. Currently, the search function queries the MySql database as soon as the first character is entered and updates the results with each subsequent character input. However, I'v ...

JavaScript heap exhausted while running Docker container

Typically, I start my application by running npm run dev. The package.json file contains a script like the one below: "scripts": { "dev": "nodemon server.ts", } Everything is working fine in this setup. I have cr ...

Angular D3 - The method 'getBoundingClientRect' is not present in the 'Window' type

Check out this StackBlitz demo I created: https://stackblitz.com/edit/ng-tootltip-ocdngb?file=src/app/bar-chart.ts In my Angular app, I have integrated a D3 chart. The bars on the chart display tooltips when hovered over. However, on smaller screens, th ...

Issues with Select2 Ajax functionality not functioning as intended

I am currently using the select2 library to create a dropdown menu with ajax functionality, but I am encountering some issues. Below is my code: $("#guests").select2({ multiple: true, minimumInputLength: 1, formatInputTooShort: fun ...

What could be causing the ajax request to not go through?

Check out this function I created that triggers an event when any inputs in an HTML form are changed. Function Snippet: function customEvent(form, element) { var timer; $(element).keyup(function () { clearTimeout(timer); if ($(ele ...

Tips for incorporating styles into react-pdf Document

I attempted to modify the width using this code, but it isn't working as expected <Document style={{width:"100px"}} file="123.pdf" ...

Update the TemplateUrl according to the URL Parameters (GET)

I've created a basic Angular code snippet (test.component.ts) that retrieves a variable from GET parameters: import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; @Component({ select ...

Stop the Text Table from being highlighted

My webpage includes a dynamic table where users can select multiple rows. jQuery events and CSS are utilized to provide visual feedback when a row is selected. However, pressing the shift key sometimes causes text to become highlighted, which is not idea ...

Ways to verify whether a vue instance is empty within a .vue file by utilizing the v-if directive

I am facing an issue with a for-loop in Vue that iterates through a media object using v-for to check if it contains any images. Everything is working correctly, but I want to display a div below the loop saying "There is no media" when the object is empty ...