Retrieve information from a URL to transmit to a different page in NextJS using Typescript and AppRouter

I'm struggling with transitioning from the Home page to the Detail page. I've successfully passed data to the URL from the Home screen, but I'm having trouble accessing it in the Detail screen. I'm working with NextJS ver 13, using Typescript and App Router. I attempted to use { useRouter } from "next/router", but it's deprecated in my version. Currently, I'm using { useParams } from "next/navigation", but I'm unsure how to implement it. Please assist me!

Below is my code: app/page.tsx:

'use client'

import Link from "next/link";
import Heading from "../Components/Heading";
import { data } from "autoprefixer";
import Router from "next/router";
import { send } from "process";
import type { NextPage } from "next";

export default function HomePage() {
  return (
    <>
      <Heading>iOS Team</Heading>
      <ul className="px-5">
        {iOS.map(member =>
          <li>
            <Link
              href={{
                pathname: "/Detail",
                query: member
              }}>{member.account}</Link>
          </li>
        )}
      </ul>
    </>
  )
}

List of members:

export const listMember = [
  {
    id: 1,
    name: "name1",
    age: 20,
  },
    {
    id: 2,
    name: "name2",
    age: 18,
  },
    {
    id: 3,
    name: "name3",
    age: 2,
  }
]

Detail screen:

'use client'

import HomePage,{ listMember } from "../page";
import { useParams } from "next/navigation";
import { useRouter } from 'next/router';

export default function DetailMember() {

    const params = useParams();
    const member = listMember.find((item) => item.id === parseInt(params.id));
    console.log(params)

    return (
        <>
        <h1>
        This is detail page of {member?.account}
        </h1>
        </>
    )
}

I tried using "useParams" but it didn't work.

Answer №1

When you passed your member object as "query" in the <Link/> component, it is recommended to use useSearchParams instead. This will allow you to access the query string easily.

const searchParams = useSearchParams();
const memberId = searchParams.get('id');

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

The Angular HttpClient Service will exclusively provide responses that have a status code of 200

I'm facing an issue with my login component where it calls an http client service to send a request to the server for logging in. Everything works smoothly when I enter valid credentials, but if I input wrong credentials, the service doesn't seem ...

The code breaks when the lodash version is updated to 4.17.4

After updating lodash to version 4.17.4, I encountered an error in Typescript that says: TypeError: _.uniqBy is not a function Uncaught TypeError: _.split is not a function The code snippet in question is as follows: import * as _ from 'lodash&apo ...

What steps should be followed for the initial deployment of a Next.js app and how should re-deployments be handled thereafter?

I recently completed a sample application in Next.js and successfully deployed it with the npm run build command. To ensure a custom server deployment, I've been referring to this informative article from Next.js documentation: Custom Server Article. ...

Unable to locate the JavaScript files within the NextJs and ReactJs project

I've encountered an issue when trying to import js files (which are libraries) in my project. I am currently using NextJS version 14.1.3 and ReactJS version 18.2.0. You can find the path to these files here Here is a glimpse of the project structure ...

Leverage Custom_Pipe within TS

I am currently working with a pipe that I have created. Here is the code: @Pipe({ name: 'searchNomES' }) export class SearchNomESPipe implements PipeTransform { transform(uos: IUo[], name?: string,): IUo[] { if (!uos) return []; if (!name) ret ...

The message "The property 'layout' is not found on the type 'FC<WrapperProps>' in Next.js" is displayed

I encountered an error in my _app.tsx file when attempting to implement multiple layouts. Although the functionality is working as expected, TypeScript is throwing an error Here is the code snippet: import Layout from '@/components/layouts&apo ...

What is the best way to showcase a standalone JSON object within the template?

I have a detailed component that is designed to show the 5-day forecast for a specific city. I have successfully retrieved the data using the http.get(Url) method. However, I am unsure of how to bind this JSON data to my view. I am familiar with displayi ...

Using React TypeScript to trigger a function upon route changes with react-router-dom

I am trying to use the useEffect hook to console log every time the location changes in my project. However, when I try to compile, I receive an error in the terminal saying Unexpected use of 'location' no-restricted-globals. I would like to fin ...

Where is the optimal location for placing a JavaScript listening function within an Angular component?

Summary: Incorporating a BioDigital HumanAPI anatomical model into my Angular 5 application using an iFrame. The initialization of the API object is as follows: this.human = new HumanAPI(iFrameSrc); An important API function human.on(...) registers clic ...

Reacting to Appwrite events in a React Native environment

My React Native application encounters an error when subscribing to realtime events. The error message reads as follows: ERROR Error: URLSearchParams.set is not implemented, js engine: hermes. appwriteClient .subscribe( `databases.${APPWRITE_DATAB ...

What is the best way to transpile TypeScript within the Astro framework?

Recently, I decided to dive into exploring Astro for a couple of upcoming projects. In my research, I delved into the script and typescript sections of the documentation (), as well as (). However, I found the workflow somewhat counterintuitive and struggl ...

Is there a different storage option for session management in Next.js besides using memory

Is there a way to utilize a storage option other than memory for next-session when memory is not ideal for production? I am looking to incorporate either file storage (preferred) or a database. ...

Display a semantic-ui-react popup in React utilizing Typescript, without the need for a button or anchor tag to trigger it

Is there a way to trigger a popup that displays "No Data Found" if the backend API returns no data? I've been trying to implement this feature without success. Any assistance would be greatly appreciated. I'm currently making a fetch call to retr ...

Encountering problems with createMediaElementSource in TypeScript/React when using the Web Audio API

Currently, I am following a Web Audio API tutorial from MDN, but with a twist - I am using TypeScript and React instead of vanilla JavaScript. In my React project created with create-react-app, I am utilizing the useRef hook to reference the audio element ...

Encountering ExpressionChangedAfterItHasBeenCheckedError during ngOnInit when utilizing Promise

I have a simple goal that I am working on: I want to display data obtained from a service in my component. This is how it used to work: In my component: ... dataSet: String[]; ngOnInit(){ this._service.getDataId().then(data => this.dataSet = da ...

Issue encountered with Next.js 13.4 and NextAuth: A Type Error stating that 'AuthOptions' is not compatible with type 'never'

Currently, I am in the process of developing a Next.js 13.4 project and attempting to configure NextAuth using the app/router. Unfortunately, I have encountered a type error that I am struggling to troubleshoot. Below is my route.ts file: import NextAuth, ...

What is the best way to generate an object in TypeScript with a variety of fields as well as specific fields and methods?

In JavaScript, I can achieve this using the following code: var obj = { get(k) { return this[k] || ''; }, set(k, v) { this[k] = v; return this; } }; obj.set('a', 'A'); obj.get('a'); // returns &ap ...

Angular Material: Enable Window Dragging Across Multiple Monitors

Exploring the usage of Angular Material Dialog or any other Popup Window Component. The functionality is mostly working as expected, with the exception of the last point. a) The original screen should not have a grey overlay, b) Users should be able to i ...

Access denied error encountered in AWS S3 while trying to restrict access based on the referring URL

I am encountering a 403-Access denied error in my Next.js app while using the new next/image feature to access S3 objects. This issue arises despite having the following policy set up: "Version": "2012-10-17", "Statement": [ ...

Installation of Shadcn UI results in the disruption of Tailwind CSS

The Shadcn UI was performing well for a few weeks until yesterday. When I ran my NextJS app on my local host, the tailwind styling stopped working. To troubleshoot, I created a new NextJS 13 app in a different location, and everything worked fine - tailwin ...