Next.js Discord

Discord Forum

location not defined in useRouter

Answered
aa55h posted this in #help-forum
Open in Discord
client component, with these imports:
import { usePathname, useRouter, useSearchParams } from "next/navigation";

any idea why it oculd be happening?
Answered by chisto
I replicated it and u get this error , it says you trying to go to a new Page when this one hasnt finish render
what you can do is put the if inside a useEffect, so it render and then moves to the new page

export default function NewPage() {
const router = useRouter();
const pathname = usePathname();
const searchParams = useSearchParams();

const createQueryString = useCallback(
(name: string, value: string) => {
const params = new URLSearchParams(searchParams.toString());
params.set(name, value);
return params.toString();
},
[searchParams]
);

useEffect(() => {
if (!searchParams.has("type")) {
router.push(pathname + "?" + createQueryString("type", "note"));
}
}, [searchParams, router, pathname, createQueryString]);

return <div>...</div>;
}
View full answer

5 Replies

I replicated it and u get this error , it says you trying to go to a new Page when this one hasnt finish render
what you can do is put the if inside a useEffect, so it render and then moves to the new page

export default function NewPage() {
const router = useRouter();
const pathname = usePathname();
const searchParams = useSearchParams();

const createQueryString = useCallback(
(name: string, value: string) => {
const params = new URLSearchParams(searchParams.toString());
params.set(name, value);
return params.toString();
},
[searchParams]
);

useEffect(() => {
if (!searchParams.has("type")) {
router.push(pathname + "?" + createQueryString("type", "note"));
}
}, [searchParams, router, pathname, createQueryString]);

return <div>...</div>;
}
Answer
oh i see
did it work?
yep
can you mark it as solved?