0

我正在尝试使用来保护 API 端点,next-auth但端点返回错误“无效的钩子调用”

以下是 API 端点的完整代码:

import Sale from '../../../../models/Sale';
import dbConnect from '../../../../utils/dbConnect';
import { useSession, getSession } from 'next-auth/client'



export default async function handler({query: {number}}, res) {

  const [session, loading] = useSession()
  await dbConnect();

  if (typeof window !== 'undefined' && loading) return null

  if (!session) {
    res.status(403)
    return <p> Unauthorized </p>
  }

  if (session) {
    const date = new Date();
    const currentYear = date.getFullYear();
    const firstYear = currentYear - number + 1;

    const sales = await Sale.find({
      orderYear: {
        $gte: firstYear
      },
      subTotal: {
        $gt: 3000
      }
    }).exec()

    if (!sales || !sales.length) {
      res.status(400).json({
        error: 'No records found for date range'
      })
    } else {
      res.status(200).json({
        data: {
          sales: sales,
          count: sales.length
        }
      })
    }
  }

}

export async function getServerSideProps(context) {
  const session = await getSession(context)
  return {
    props: {
      session
    }
  }
}

这是完整的错误:

Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.

我已经阅读了文档,但我不明白我在这里对钩子的使用是不正确的。

我应该如何使用useSession()钩子?

4

1 回答 1

2

正如错误提示的那样,您只能在React功能组件内调用钩子。

这个函数不是一个React组件,它是一个 API 路由,就像你说的那样。我对 NextJS 不是很了解,但是您需要的功能可能存在于其他地方。您从一个名为next-auth/clientkinda 的库中导入它的事实引起了怀疑。

于 2021-05-19T21:22:53.687 回答