koole / react-sanctum

Easily hook up your React app to Laravel Sanctum and Laravel Fortify
MIT License
152 stars 26 forks source link

TypeError: Cannot read property 'useContext' of null #185

Closed harrisonratcliffe closed 1 year ago

harrisonratcliffe commented 1 year ago

Trying to use react-sanctum in middleware and I'm getting the following error: TypeError: Cannot read property 'useContext' of null

const { authenticated } = useSanctum();

I have imported useSanctum().

Any ideas?

koole commented 1 year ago

Are you sure React is installed correctly and available? The only place useContext is ever used is on the following line: https://github.com/koole/react-sanctum/blob/fa5636e03c18546d45101fe1ca67a0fa1a7db469/src/useSanctum.ts#L10

The only thing I can think of is that React itself is somehow null.

harrisonratcliffe commented 1 year ago

Yeah, I use Next.js specifically. This is my full middleware.js file:

import { useSanctum } from 'react-sanctum';

export function middleware(request) {
    if (request.nextUrl.pathname.startsWith('/login')) {
        const { authenticated } = useSanctum();

        if (authenticated === true) return request.redirect(new URL('/dashboard, request.url))
    }
}
koole commented 1 year ago

I'm not familiar enough with Next.js middleware's to be able to solve this problem. This might better be asked on StackOverflow, as I don't think it's a react-sanctum issue.

If it turns out to be, feel free to send an update and I'll reopen this issue.