Sharing information between different pages in NEXT.js version 14

After performing a fetch and receiving a successful response containing data as an object, I use router.push to redirect the page to another one where I want to display the fetched data.

const handleSubmit = async (event: any) => {
    event.preventDefault(); 
  
    try {
      const response = await fetch('http://localhost:8080/api/auth/signin', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(formData)
      });
  
      const responseData = await response.json();
  
      
      if (responseData) {
        console.log('Login successful!', responseData);
        localStorage.setItem('accessToken', responseData.token);
        localStorage.setItem('username', responseData.username);
        
  
        toast({
          description: "Login successful"
        });
  
        
        router.push({
          pathname: '/', 
          query: responseData  
        });
  
        setFormData({
          username: '',
          password: ''
        });
      } else {
        // If the response is not as expected
        console.error('Unexpected API response:', responseData);
        setError('Invalid credentials. Please try again.');
      }
  
    } catch (error) {
      console.error('Error during login:', error);
    }
  };

I'm encountering errors with the router.push, but how can you effectively pass a response between different pages?

Answer №1

When utilizing the App Router, if you want to pass data from the parent page, you can specify a search parameter in the parent page:

'use client'

import { useRouter, useSearchParams } from 'next/navigation';

export default function ParentPage() {
  // ...

  const router = useRouter();

  const searchParams = useSearchParams();
  
  const handleSubmit = async (event: any) => {
    // ...

    toast({
      description: "Login successful"
    });

    // retrieve current search parameters
    const params = new URLSearchParams(searchParams.toString());
    
    // set a new parameter using the `data` key: `key: value`
    params.set(data, responseData);

    // stringify the parameters for use in `router.push`
    router.push(`/?${params.toString()}`);
  
    // remaining code
  };

  // ...
}

In the child page, extract the data from the search parameters like this:

'use client'

import { useSearchParams } from 'next/navigation';

export default function ChildPage() {
  const searchParams = useSearchParams();

  // get the `data` search parameter
  const data = searchParams.get('data')

  // remaining code
}

This explanation should be beneficial.

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

Output Scalable Vector Graphics (SVG) content on a webpage

I need to include an SVG element in my Angular 2+ code. My goal is to provide users with the option to print the SVG element as it appears on the screen. <div class="floor-plan" id="printSectionId2" (drop)="onDrop($event)" (dragover)="onDragOver ...

Transitioning from MVC to Angular 2 and TypeScript: A Step-by-Step Guide

Seeking guidance as I venture into the world of Angular. My goal is to pass a string variable 'element' to my UI and utilize it. However, I am unsure about how to go about passing it inside main.js and beyond. How can I transfer a variable to a t ...

Troubleshooting Angular: Unidentified property 'clear' error in testing

I've implemented a component as shown below: <select #tabSelect (change)="tabLoad($event.target.value)" class="mr-2"> <option value="tab1">First tab</option> <op ...

Obtain the dimensions (width and height) of a collection of images using Angular and TypeScript

Currently, I am facing an issue with my image upload functionality. My goal is to retrieve the width and height of each image before uploading them. However, I've encountered a problem where my function only provides the dimensions for the first image ...

Utilizing Higher Order Components (HOC) and the useSessionContext hook to address the flickering issue with Supabase Authentication redirection

I am currently integrating Supabase for authentication in my web application. An issue I have encountered is that when I am already logged in and attempt to access the login page for testing purposes, there is a brief display of the login page before being ...

Show a roster of individuals by inputting values that will populate the list with their names

I'm attempting to showcase a list of users by taking the value from an input and using it as a parameter in a get() method. After receiving the response from the get() method, I am pushing it into an object and then trying to display this object in th ...

Interface displaying auto-detected car types

I have a setup that looks like this: interface ValueAccessor<T> { property: keyof T; getPropertyValue: (value: any) => value; } I am trying to figure out how to define the correct type and replace the any when I want to provide a custom ...

Issues with implementing routing children in Angular 8

Currently, I am in the process of building a website and facing some issues with implementing the admin section. Within my admin module, I have various components such as login, dashboard, products, etc. However, I am encountering an issue where the childr ...

Setting up Next.js rendering within Express routing: A step-by-step guide

app.js const express = require('express'); const next = require('next'); const port = parseInt(process.env.PORT, 10) || 3000; const dev = process.env.NODE_ENV !== 'production'; const app = next({ dev }); const handle = app.ge ...

The 'subscribe' property is not available on the type '() => Observable<any>'

File for providing service: import { Observable } from 'rxjs/Rx'; import { Http, Response} from '@angular/http'; import { Injectable } from '@angular/core'; import 'rxjs/add/operator/Map'; @Injectable() export clas ...

Issue with applying value changes in Timeout on Angular Material components

I'm currently experimenting with Angular, and I seem to be struggling with displaying a fake progress bar using the "angular/material/progress-bar" component. (https://material.angular.io/components/progress-bar/) In my "app.component.html", I have m ...

How can I verify the validity of a regular expression in Typescript without encountering a syntax error?

I am facing an issue with my code where I load a set of regular expressions from an external source. My goal is to determine if a given string is a valid regex without causing the application to crash due to a syntax error. Despite trying to use try/catch ...

Exploring Angular data iteration with Tab and its contentLearn how to loop through Tab elements

Upon receiving a response from the API, this is what I get: const myObj = [ { 'tabName': 'Tab1', 'otherDetails': [ { 'formType': 'Continuous' }, { 'formType& ...

Having trouble getting the tailwindcss Google font link tag to apply properly

When I use the @import in the tailwind css file, it works fine. However, when I try to add the font using the <link> tag in _document.jsx, it fails to work properly. In Chrome dev tools, it shows that the classes are applied but the fallback font is ...

Tips for ensuring proper dependency regulations in javascript/typescript/webpack

In essence, I am in search of a method to limit dependencies, similar to how one would manage different projects (libraries) in Java or C#. Think of it as friend or internal access modifiers. I'm considering various approaches to accomplish this (suc ...

cleaner urls using nextjs routing

Currently working on developing a fresh marketing platform for my company utilizing next.js, and encountering some hurdles with URLs. Essentially, I've created a custom API route to retrieve data from our internal database using Prisma: getAllDealers ...

How can I send dynamic props between pages using Next.js?

I am currently exploring Next.js and attempting to create a page (index.js) that fetches data about different countries and then displays this information. I would like each country element displayed on the page to have a button that leads to another page ...

Encountered a bun runtime error stating "Possibly require an `extends React.JSX.IntrinsicAttributes` constraint for this type parameter."

I have a good understanding of ReactJS, but this topic seems to be more advanced. I am working with generics in TypeScript and have the following code: export const withPopover = <T,>(WrappedComponent: React.ComponentType<T>) => { const ...

Next.js focuses solely on rendering markup and does not run any custom code

I am in the process of creating a website, where currently the only functionality available is to change themes by selecting an option from a dropdown menu (the theme is an attribute that uses CSS variables). Everything was functioning properly, however t ...

Images displaying correctly in Next.js development environment, but failing to load on Github Pages production site

I am currently using Next.js alongside Tailwind CSS and I'm encountering an issue while attempting to set a background image for a specific div. Oddly enough, the image appears to load correctly in development mode, but fails to display when deployed ...