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
Do you have import { useRouter } from "next/router"; ?
If so, maybe try to use ‘next/navigation’ instead coupled with router.pathname.
Within the
app
router, setting and grabbing query parameters is not done by theuseRouter
hook anymore. You should set it yourself:And grab it using the
useSearchParams
hook: