user3887366
user3887366

Reputation: 2594

React auth using useState for route

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?

Upvotes: 3

Views: 911

Answers (1)

Syder
Syder

Reputation: 372

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}) => {
....

Upvotes: 1

Related Questions