skip to Main Content

I am sending an object called footprintsData from my question screen to a result screen as shown below:

const footprintsData = {
  carFootprint: roundedCarFootprint,
  electricityFootprint: roundedElectricityFootprint,
  gasFootprint: roundedGasFootprint,
  commuteFootprint: roundedCommuteFootprint,
  airTravelFootprint: roundedAirTravelFootprint,
  totalFootprint: parseFloat(totalFootprint.toFixed(2)),
};

router.push({
  pathname: "/results",
  query: { footprintsData: footprintsData },
});

At the result screen, I am trying to read the data as follows:

const router = useRouter();
const { totalFootprint, carFootprint, electricityFootprint, gasFootprint, commuteFootprint, airTravelFootprint } = router.query;

However, it is giving the following error:

Unhandled Runtime Error
TypeError: Cannot destructure property 'totalFootprint' of 'router.query' as it is undefined.

I am using Next.js version 14.1.1 and have tried the following methods to send my data object:

console.log("Individual Footprints:", footprintsData);

router.push('/result', query:{carFootprint});

router.push('/test?totalfootprint=' + totalFootprint, { totalFootprint: totalFootprint });

<Link href={{ pathname: "/result", query: footprintsData }}></Link>

<Link href={{ pathname: "/test", query: { totalfootprint: 'totalFootprint' } }}></Link>

<Link href="/result">MOVETORESULTS</Link>
router.push({
   pathname: '/results',
   query: { footprintsData: footprintsData },
});

but the same error persists throughout. I even made a test screen with nothing else being displayed but the object was still not being received properly.

2

Answers


  1. Do you have import { useRouter } from "next/router"; ?

    If so, maybe try to use ‘next/navigation’ instead coupled with router.pathname.

    Login or Signup to reply.
  2. Within the app router, setting and grabbing query parameters is not done by the useRouter hook anymore. You should set it yourself:

    router.push("/results?footprintsData=" + JSON.stringify(footprintsData));
    

    And grab it using the useSearchParams hook:

    import { useSearchParams } from 'next/navigation'
    
    const searchParams = useSearchParams();
    const footprintsData = JSON.parse(searchParams.get("footprintsData"));
    console.log(footprintsData);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search