Transferring data between pages in Next JS using App Route and Typescript

Seeking assistance to extract data from an array on one page and display it on another page. I am working with NextJs, Typescript, and AppRoute.

Code in app/page.tsx:

import Image from 'next/image'
import Link from 'next/link'

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

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

Code in app/Detail/page.tsx:

import HomePage from "../page";

export default function Detail() {
    return (
        <>
            <h1> 
                This is detail page of {HomePage.listMember.name}
            </h1>
        </>
    )
}

Attempted using route but encountered issues.

Answer №1

If you want to retrieve the list from your main page, start by exporting it:

export const memberList = [
  {
    id: 1,
    name: "John",
    age: 30,
  },
    {
    id: 2,
    name: "Jane",
    age: 25,
  },
    {
    id: 3,
    name: "Mike",
    age: 40,
  }
]

Next, on the detail page, access the query parameter and locate the parameter using this method:

import { useSearchParams } from 'next/navigation'
import HomePage, { memberList } from "../page";

export default function Detail() {
const searchParams = useSearchParams()
const name = searchParams.get('name')

  const member = memberList.find(member => member.name === name);

    return (
        <>
            <h1> 
                Welcome to the detail page of {member?.name}
            </h1>
        </>
    )
}

Answer №2

Modify to

export const memberList = [...
...
import {memberList } from "../page";

export default function Detail() {
    return (
        <>
            <h1> 
                Welcome to the detailed page of {memberList.name}
            </h1>
        </>
    )
}

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

Adding dynamic metadata to a specific page in a next.js app using the router

I was unable to find the necessary information in the documentation, so I decided to seek help here. My goal is to include metadata for my blog posts, but I am struggling to figure out how to do that. Below is a shortened version of my articles/[slug]/page ...

Concealing tab bars on Ionic 2 secondary pages

In my Ionic Bootstrap configuration, I have the following setup: { mode: 'md', tabsHideOnSubPages: true } However, despite having this setting in place, the tabs still appear on some sub-pages. It seems to be happening randomly. Is there ...

Tips for resolving a typescript Redux connect error related to ActionCreatorsMapObject

Encountering typescript error: ERROR in [at-loader] ./src/app/components/profile/userProfile/_userMain.tsx:130:37 TS2345: Argument of type 'typeof "/usr/src/app/src/js/src/app/redux/actions/sessionActions"' is not assignable to parameter of ...

Exploring the power of SCSS modules within Next.js

In my next.js project, I am using next-int to set up languages. Typically, I have components with a module.scss file each. However, I want to avoid duplicating my scss files for styling the Arabic version of my site. The main differences come down to align ...

Angular 2 - retrieve the most recent 5 entries from the database

Is there a way to retrieve the last 5 records from a database? logs.component.html <table class="table table-striped table-bordered"> <thead> <tr> <th>Date</th> <th>Logging ...

The functionality of the Request interface appears to be malfunctioning

Hey there, I'm currently working on building an API using Express and TypeScript. My goal is to extend the Request object to include a user property. I've done some research on Google and found several posts on StackOverflow that explain how to d ...

When executing the release command in Ionic 3, the Angular AoT build encountered a failure

Struggling to get my Sony Z2 smartphone app running. Command used: ionic build android --prod --release Error displayed in console: typescript error Type CirckelmovementPage in C:/Users/fearcoder/Documents/natuurkundeformules/src/pages/cir ...

The page could not be generated due to a server error with the syntax. More specifically, an Unexpected token 'export' caused a SyntaxError

Encountering an issue while attempting to retrieve data using getServerSideProps. Seeking assistance, thank you! Server Error SyntaxError: Unexpected token 'export' This error occurred during the page generation. Any console logs will be shown ...

What is the best way to convert this into a distinct function using typescript?

Is there a way to create a single method in Protractor or Webdriver API that can get the browser width and height? const getWindowWidth = async () => { const size = await browser.manage().window().getSize(); return size.width; }; I need this metho ...

React error #425: Timezone formatting causing minification issue

Encountering a strange issue that seems to only occur on Vercel. The error message reads: Uncaught Error: Minified React error #425; visit https://reactjs.org/docs/error-decoder.html?invariant=425 for the full message or use the non-minified dev environme ...

What is the method for transferring properties in next JS?

When I try to pass a property while invoking a component, it doesn't seem to work as expected. I'm new to next JS and this concept is confusing me. //Example Component const ExampleComponent: React.FC = (props) => ( <section className= ...

Set the array as the object attribute

Transitioning my app from AngularJs to Angular 4 has been quite a challenge. I've noticed that the type of statements I frequently used in my code are now failing in Angular 4 (TypeScript): Update: The following lines were previously used in Angular ...

The NextSJ configuration error: Webpack encountering a ModuleParseError due to an unexpected character in the module parsing process

I encountered an error while trying to build my Next.js app or start the server using the `yarn dev` command. This issue seems to have arisen after installing and then uninstalling the next-less plugin. I've tried reverting the code back to its previo ...

What is the methodology behind incorporating enumerations in typescript?

I've been curious about how typescript compiles an enumeration into JavaScript code. To explore this, I decided to create the following example: enum Numbers { ONE, TWO, THREE } Upon compilation, it transformed into this: "use strict ...

Configuring modules using Sass, CSS-Modules, Webpack, React, and TypeScript

I'm facing an issue with extracting types from my .scss files. I've tried various configurations and solutions, but nothing seems to work. Specifically, my goal is to utilize modules in a React app with TypeScript. Below is my webpack configura ...

The TypeScript error "File 'XXX' is not recognized as a module" is preventing successful compilation

Is there a way to import a module from an external file into another TS file? Even after following the steps, when I tried to do so in VSCode, it gave me an error saying that the file 'XXX' is not a module: Here's the error I encountered I ...

Tips for creating a typescript typeguard function for function types

export const isFunction = (obj: unknown): obj is Function => obj instanceof Function; export const isString = (obj: unknown): obj is string => Object.prototype.toString.call(obj) === "[object String]"; I need to create an isFunction method ...

Show the values in the second dropdown menu according to the selection made in the first dropdown menu using Angular 8

My goal is to retrieve data and populate two dropdowns based on user selection. However, the code I've written isn't giving me the desired output and instead, errors are occurring. Being new to Angular, I would appreciate a review of my code. Her ...

Difficulty accessing context.params query in Next.js Dynamic Path

I've almost completed setting up a dynamic page in Next.js using getStaticPaths(), but I'm running into an issue with the getStaticProps() function not referencing the URL query correctly to load the relevant information. Here is my code: //Get ...

TypeScript: Despite declaring specific types, generic functions still treat parameters as "any"

When using TypeScript 4.4.3, I am looking to specify the types of function parameters for a function that returns a generic. However, TypeScript seems to be treating the parameters as any when working with functions that involve generics. Here's a si ...