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

Issue encountered: "TypeError: .... is not a function" arises while attempting to utilize a component function within the template

Within my component, I am attempting to dynamically provide the dimensions of my SVG viewBox by injecting them from my bootstrap in main.ts. import {Component} from 'angular2/core'; import {CircleComponent} from './circle.component'; i ...

The Angular @Input directive may be prone to receiving inaccurate model data

I am currently working on setting up @Input for my component using a model that resembles the following: interface Car { sail?: never tires: number weight: number } interface Boat { tires?: never sail: boolean weight: number } exp ...

Removing API request in React.js

My approach: deleteSample = () => { this.sampleService .deleteCall(this.props.id) .then((response) => { window.location.reload(false); }) .catch((error) => { console.log ...

Passing data from child components to parent components in NextJs using Typescript

I have created a new component <ConnectWallet setConnected={(t: boolean) => console.log(t)}> <>test</> </ConnectWallet> The component is initialized as follows import { useState, useEffect } from ' ...

Efficiently process and handle the responses from Promise.all for every API call, then save the retrieved data

Currently, I am passing three API calls to Promise.all. Each API call requires a separate error handler and data storage in its own corresponding object. If I pass test4 to Promise.all, how can I automatically generate its own error and store the data in ...

Creating TypeScript atom packages

Has anyone successfully implemented this before? I couldn't locate any assistance for it. If someone could provide references to documentation or existing code, that would be great. I know that Atom runs on Node and that there is a TypeScript compil ...

When working with Angular/Typescript, the error message "compilation of 'export const' is not possible

Embarking on creating my very own Angular library, I took the first step by adding a service without any issues. The challenge arose when I decided to move a constant to a file named tokens.ts for the service to reference. Following this change, the build ...

Template URI parameters are being used in a router call

Utilizing the useRouter hook in my current project. Incorporating templated pages throughout the application. Implementing a useEffect hook that responds to changes in the router and makes an API call. Attempting to forward the entire URL to /api/${path ...

How to access parent slider variables in an Angular component

I've developed a slider as the parent component with multiple child components. See the demo here: https://stackblitz.com/edit/angular-ivy-gcgxgh?file=src/app/slide2/slide2.component.html Slider in the parent component: <ng-container *ngFor=&quo ...

Having trouble with the Angular Language Service extension in VS Code for Angular-16?

Upon transitioning to Angular 16, I encountered errors while attempting to edit the components HTML due to the malfunctioning of the Angular Language Service extension. [Info - 09:41:11] Angular language server process ID: 18032 [Info - 09:41:11] Using t ...

Retrieving an Observable within an Observable is a feature found in Angular 9

Seeking a solution to return an Observable nested within another Observable. Although I've tried using the pipe and map operators, it doesn't appear to be functioning correctly for me. What could be causing the issue? My development environment ...

Obtaining Input Field Value in Angular Using Code

How can I pass input values to a function in order to trigger an alert? Check out the HTML code below: <div class="container p-5 "> <input #titleInput *ngIf="isClicked" type="text" class="col-4"><br& ...

Display the initial occurrence from the *ngIf statement

Is there a way to display only the first match from the *ngIf? I am currently using an object loop with *ngFor, where I have multiple items with the same Id but different dates. I need to filter and display only the item with the most recent date and avo ...

What is the process for retrieving information from a JSON document?

When working on my project using Next.js, I encountered an issue with fetching and displaying data from a JSON file named mainMenu. Could someone please guide me on how to correctly implement this? I have shared my code below: function MyApp({ Component, ...

The module "ng-particles" does not have a Container component available for export

I have integrated ng-particles into my Angular project by installing it with npm i ng-particles and adding app.ts import { Container, Main } from 'ng-particles'; export class AppComponent{ id = "tsparticles"; /* Using a remote ...

What is the significance of var-less variables in TypeScript class definitions?

Why is it that when creating a component class in Angular2, we don't need to use var when declaring a new variable? For example: @Component({ selector: 'my-app', template: ` <h1>{{title}}</h1> ` }) export class AppCo ...

The error message states that the object literal can only define properties that are known, and in this case, 'tailwindcss' is not recognized in the type 'NuxtConfig'

I'm facing an issue in my nuxt.config.ts file while trying to set up a custom tailwind css path. The error I keep encountering can be viewed here. Can someone guide me on how to properly create the custom tailwind css path in my nuxt.config.ts file? ...

What is the best way to utilize a component's property within a parent abstract class?

Custom Class: export abstract class CustomClass { constructor(); customMethod() { // accessing the name input of SomeComponent here; } } Some Component: export class AnotherComponent extends CustomClass { @Input() name: string; constru ...

The console log is displaying 'undefined' when trying to access Node.js fs

Recently, I was engrossed in developing a Next.js blog. After completing the frontend, I shifted my focus to building the backend using Next.js. ./pages/api I created a new file: ./pages/api/blogs.js To test my backend functionalities, I generated some J ...

The Dynamic Duo: Typescript and Knex

I'm new to TypeScript and currently working on a node application using Express, Postgresql, and Knex. I'm a bit confused about when to apply type definitions in my code. Looking at other projects for guidance has left me even more puzzled as to ...