我正在尝试使用来保护 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()
钩子?