0

I have a PrivateRoute component,

interface Props {
    path: string,
    exact: boolean,
    component: React.FC<any>;
}

const PrivateRoute: React.FC<Props> = ({ component, path, exact }) => {
    return (
        <Route
            path={path}
            exact={exact}
        >
            {
                getCookie('name').length !== 0 ? component : <Redirect to="/login" />
            }
        </Route>
    );
}

But when I try to use useState hook inside a PrivateRoute, I get the invalid hook call error.

Example,

const [some, setSome] = useState(true);
// Calling this inside a private route will throw an error!

How to solve this?

Edit

This is how PrivateRoute is used,

<Switch> // from react-router-dom
   <Route path="/login" component={Login} />
   <PrivateRoute path="/" exact component={Home} />
</Switch>

Edit 2

codesandbox

Nithin Sai
  • 840
  • 1
  • 10
  • 23
  • for ref https://stackoverflow.com/questions/56663785/invalid-hook-call-hooks-can-only-be-called-inside-of-the-body-of-a-function-com – John Lobo Jun 12 '21 at 12:21
  • How do you use `PrivateRoute` component in the application? – aleksxor Jun 12 '21 at 12:40
  • @aleksxor can you check now?? – Nithin Sai Jun 12 '21 at 15:02
  • And where do you insert line with `useAuthContext` when it gives you the error? – aleksxor Jun 12 '21 at 17:16
  • @aleksxor I use ```useAuthContext``` inside the ```component``` passed to ```PrivateRoute``` (here ```Home```). ContextProvider wraps around the ```Switch``` – Nithin Sai Jun 13 '21 at 14:17
  • Well, I can't see any problems using hooks inside a Route component. https://codesandbox.io/s/usecontext-inside-route-so-example-qiryj?file=/src/route.tsx – aleksxor Jun 13 '21 at 14:37
  • @aleksxor smh I found the actal error https://codesandbox.io/s/usecontext-inside-route-so-example-forked-9dogx?file=/src/SecretPage.tsx – Nithin Sai Jun 13 '21 at 15:42

1 Answers1

1

This works now.

export const PrivateRoute: React.FC<{
  component: React.FC<any>;
  path: string;
  exact: boolean;
}> = ({ component, path, exact }) => {
  const auth = useAuthProvider();

  return auth.isAuth ?  <Route path={path} exact={exact} component={component}/> : <Redirect to="/" />
};
PRATIK NAIK
  • 489
  • 3
  • 7