Search code examples
typescriptnext.jsapp-router

Get data from URL to pass to another page in NextJS with Typescript, AppRouter


I'm having changing page from Home to Detail, i already passed data to URL from Home screen, but in Detail screen i can not get it. I'm using NextJS ver 13, with Typescript and App Router. I tried to use { useRouter } from "next/router" but it has deprecated in my version. I'm now using { useParams } from "next/navigation" but I'm not clear how to use it. Please help me !!!

Here's 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 member:

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>
        </>
    )
}

Tried to use "useParams" but not work


Solution

  • Since you passed in your member object in the <Link/> component as "query", you should be using useSearchParams instead, which will get the query string.

    const params = useSearchParams();
    const id = params.get('id');