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

Time:12-03

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

But bellow error occured:

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 '../bussiness/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?

CodePudding user response:

You can avoid this by using

import Router from 'next/router';

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

  • Related