Reputation: 11
I have a component (App) where I store hook state if user is logged in, I want user to be logged when /dashboard is rendered and I want to keep that info even when /dashboard is unmounted. I use it in DefaultNavbar to determine right buttons. In my code state of isLogged is set to true when I am in /dashboard, but when I render /account the state of isLogged is again false. How to keep the value of isLogged when Dashboard is unmounted? Here is the code of App.
function App() {
const [isLogged, setIsLogged] = useState(false);
return (
<div className="App">
<DefaultNavbar isLogged={isLogged}/>
<Router>
<Switch>
<Route exact path="/">
<Home />
</Route>
<Route path="/createUser" >
<CreateUser />
</Route>
<Route path="/dashboard">
<Dashboard setIsLogged={setIsLogged} />
</Route>
<Route path="/redirectAfterLogin" >
<RedirectAfterLogin />
</Route>
<Route path="/account" >
<Account />
</Route>
</Switch>
</Router>
<Footer />
</div>
);
}
Code of Dashboard:
export default function Dashboard(props) {
useEffect(() => {
props.setIsLogged(true);
return () => {
props.setIsLogged(true);
}
}, [])
return (
<div>
</div>
)
}
And code of DefaultNavbar:
export default function DefaultNavbar(props) {
return (
<div>
<Navbar bg="warning" >
<Navbar.Brand>
<Image src={logo} />
</Navbar.Brand>
<Nav className="ml-auto">
{!props.isLogged &&
<Button variant="outline-success" href="/">Dowiedz się więcej o nas</Button>
}
{props.isLogged &&
<Button variant="outline-success" href="/account">Moje konto</Button>
}
</Nav>
</Navbar>
</div>
)
}
Upvotes: 1
Views: 68
Reputation: 203482
You are rendering react-bootstrap Button
components with a href
prop which renders an <a>
element. This reloads the page and your app, so the isLogged
state is reset.
Import the Link
component from react-router-dom
and render it in the react-bootstrap
Button
component.
import { Link } from 'react-router-dom';
...
<Button
as={Link}
to="/account"
variant="outline-success"
>
Test
</Button>
DefaultNavBar
function DefaultNavbar(props) {
return (
<div>
<Navbar bg="warning">
<Navbar.Brand>
<Image src={logo} />
</Navbar.Brand>
<Nav className="ml-auto">
{props.isLogged ? (
<Button variant="outline-success" as={Link} to="/account">
Moje konto
</Button>
) : (
<Button variant="outline-success" as={Link} to="/">
Dowiedz się więcej o nas
</Button>
)}
</Nav>
</Navbar>
</div>
);
}
Upvotes: 1