I'm trying to change the browser URL and render the desired component based on some condition. however, I'm able to change the URL after successful login and land the user to /home page but when I'm trying to change the URL on button click, it hits the /accounts URL and changes to /home again.
App.js
<Route exact path="/accounts" component={Accounts} />
<Route exact path="/home" component={Home} />
<Route exact path="/" component={Login} />
</Switch>
after successful login from component A, I'm executing below piece of code which renders home components
setInterval(() => {
history.push("/home")
}, 300);
once the user performs a button click in /home i'm executing below piece of code to change the url and render accounts component.
function showAccountsTransactions () {
history.replace("/accounts")
}
return (
<div className={classes.root}>
<Fab onClick={showAccountsTransactions}>
Show Account and Transactions
</Fab>
</div>
but i could see that onClick, the url is getting changed to /accounts and switches back to /home. Could you guys please suggest some idea.
Looks like you have got yourself a scheduler.
setInterval(() => {
history.push("/home")
}, 300);
The code above resets the URL to /home
at every 300ms(0.3s), no matter where you go.
setTimeOut
and setIntervals
are never made to be used for routing. so Don't.
A few more best practices would be to avoid using history.replace()
and use history.push()
instead. Its not a right idea to change history stack of routes.
Also when you use <Switch>
, there is no need to use exact
everywhere. They are just alternatives for each other, at different circumstances.