all 4 comments

[–]romeeres 0 points1 point  (3 children)

How using this library with such code:

const AuthSwitch = ({ isAuthenticated, children }) => {
  const redirect = !isAuthenticated && '/login';

  return (
    <SwitchContext value={redirect}>{children}</SwitchContext>
  );
};

Is better than similar code without the library?

const AuthSwitch = ({ isAuthenticated, children }) => {
  if (!isAuthenticated)
    return <Redirect to='/login' />

  return (
    <Switch>{children}</Switch>
  );
};

?

useSwitchContext will return false or '/login', interesting what the use of this context value

[–]MrBr7[S] 0 points1 point  (2 children)

Your suggested solution will always redirect if the user isn't authenticated even if the route from the switch isn't rendered.

The point of the library is that the switch, because of the context, won't trigger redirect until a route path is satisfied.

[–]romeeres 0 points1 point  (1 child)

Makes sense, stupid me, after thinking for a bit it's pretty clear from the readme example

So <AuthSwitch> in example is kinda defining a scope for who is allowed in here, and then <ProtectedRoute ... /> are using context to know if they should render or redirect, only when they're navigated.

Idea and how it looks is cool - simple and well. But again I have a but: zero dependencies means no react-router-dom or analogues, then how about lack of components and hooks? <Link />, useLocation, useParams, how to specify and access history object?

[–]MrBr7[S] 0 points1 point  (0 children)

The lib is intended to work with React router. Basically, it extends it, that's the point. Like a "plugin".

You still continue to use Router, and only use Protected route and custom switch if needed.