DEV Community

loading...

Auth middleware with React navigation

themisir profile image Misir Jafarov ・1 min read

I want to create auth middleware to check if the user is authorized, continue to page if is not then show the sign-in screen.

I have a bottom tab navigator. I want to apply this middleware to My Profile tab on that navigator.

So I tried to make that using hooks but it doesn't work.

export const authMiddleware = (PageComponent, pageName, backTo) => (props) => {
    var auth = useContext(AuthContext);
    if (auth.token) {
        return <PageComponent {...props} />
    } else {
        useEffect(() => {
            props.navigation.navigate('SignIn', { redirect: { to: pageName }, back: { to: backTo } })
        })
        return <View />
    }
}

The sign-in the page only went up once (after the first render).

What's your idea to make it works?

Discussion (1)

Collapse
chiangs profile image
Stephen E. Chiang

You shouldn't have a hook inside a conditional. Try upgrading to Scripts 3.0 and the linter should mention that.

You can also refer to the rule of 3

Instead, have the hook run on initial load every time using the empty dependency array argument and inside that hook run the conditional logic.

And instead of returning navigator.. Just return an <authorized> or <unauthorized> component that wraps the relevant routes. In your case the unauthorized component would just wrap the sign in page... If you are using a 3rd party sign in page then you can just return the route via their specifications.

Here's an example

From

Forem Open with the Forem app