#"NextRouter was not mounted" with custom useRouter hook

4 messages · Page 1 of 1 (latest)

earnest fox
#

when using a custom hook that uses useRouter inside it, NextRouter becomes unavailable and I got the "NextRouter was not mounted" error

even with this hook I got the error:

// hooks/use-my-router.ts
export const useMyRouter = () => {
  const router = useRouter()
  return router
}

if in my component I change the useMyRouter call by useRouter, the errors goes away and I got the correct router object

versions
"storybook": "7.0.2",
"next": "13.3.0",

dusky dirge
#

@storm vessel ?

earnest fox
#

FYI, the hook useMyRouter is defined in another package, if I define the useMyRouter in the same file of the component I want to create a story for, it works
dont get how the fact that the component is defined in another package could produce this error, in all case the custom PageRouterProvider from storybook is defined

earnest fox
#

follow up on this issue in case someone has the same issue as I:
I've ended up mocking my custom hook in webpack config to use the real next useRouter function:

// .storybook/main.ts
const config = {
  ...,
  webpack: config => {
    config.resolve = {
      ...config.resolve,
      alias: {
        'hooks/use-my-router': require.resolve('./__mock__/use-custom-hook.js')
      }
  }
export default config

// __mocks__/use-custom-hook.js
import { useRouter } from 'next/router'

export const useMyRouter = useRouter