Fixing `NextRouter was not mounted` in Next.js
I wanted to programmatically change the route. So I looked up how to do it on the docs and found this:
'use client';
import { useRouter } from 'next/navigation';
export default function Page() {
const router = useRouter();
return (
<button type="button" onClick={() => router.push('/dashboard')}>
Dashboard
</button>
);
}
Great. So I called useRouter()
in my code, and let VSC import it for me:
I saw that the package names were different. I assumed the documentation was up to date. So I went with next/router and got this error on my page:
Clicking the link explains that it can happen in unit tests, in which case we should mock the router. Except I am not running a unit test. I tried both packages suggested by VSC, and got the same error.
Eventually I googled it, and they recommended to import useHistory from 'next/navigation'
, like the doc said. And indeed, it fixed it! I wonder why VSC did not suggest it at all.