user18209107
user18209107

Reputation:

Error: Invalid hook call. Hooks can only be called inside of the body of a function component. When using next/router

I have a specific scenario where I need to redirect to specific page using next/router

But this error occurred:

Error: Invalid hook call. Hooks can only be called inside of the body of a function component.

All my code in index.tsx are:

import { Axios } from '../axios'
import { Languages } from '../business/language'
import { useRouter } from 'next/router'

export async function DispatchApi({
  address,
  sendedData,
  lan = Languages.fa,
  method,
}: {
  address: string
  sendedData: string
  lan: Languages
  method: 'POST' | 'GET'
}) {
  let data = JSON.parse(sendedData)
  const router = useRouter()
  
  let useAxios = Axios.interceptors.request.use((config) => {
    router.push('login')
    return config
  })
  return await Axios({
    url: address,
    data,
    method,
    headers: {
      accept: '*/*',
      'Accept-Language': lan,
      'Content-Type': 'application/json',
    },
  }).then(({ data }) => data)
}

But how can I fix problem. Is there any specific configuration?

Upvotes: 2

Views: 100

Answers (1)

m4china
m4china

Reputation: 240

You can avoid this by using

import Router from 'next/router';

It has the same properties as the object returned from useRouter()

Upvotes: 1

Related Questions