Invalid hook call in API route
I'm trying to secure an API endpoint using next-auth
but the endpoint is returning the error 'Invalid hook call'
Here's the complete code from the API endpoint:
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
}
}
}
This is the full error:
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.
I've read the docs, and I don't understand how my use of a hook is incorrect here.
How should I probably use the useSession()
hook?
Just as the error suggest, you can only call hooks inside React
functional components.
This function is not a React
component, it's an API route, like you said. I am not really knowledgeable in NextJS, but perhaps the functionality you need here exists in some other place. The fact you're importing it from a library called next-auth/client
kinda raises suspicion.