React auth using useState for route

Viewed 251

I'm trying in a personal project to learn react not to use redux only hooks. So I've got a simply custom hook

const useAuth = () => {
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  return { isAuthenticated, setIsAuthenticated };
};

to use for set the auth to true

but it doesn't work.

Here you can see an example

https://stackblitz.com/edit/react-rky7dn?file=src%2Flogin.js

Can anyone tell me what's wrong please?

1 Answers

You defined it right but using it wrong. You want to do use the hook only once in your App.js and then pass down "setIsAuthenticated" to your Login.js (and not call the hook again)

//App.js
const { isAuthenticated, setIsAuthenticated } = useAuth();
...
<Route path="/login">{!isAuthenticated ? <Login setIsAuthenticated={setIsAuthenticated}/> : <Redirect from="/login" to="/" />}</Route>
//Login.js
const Login = ({setIsAuthenticated}) => {
....
Related