Reload page if click to same path - reactjs

:)
I'm trying to reload browser (with location.reload();) if user click in <Link> for the the same path, where it already.
Example:
I have a menu:
- Home
- Contact
- About
When user click in 'Contact', he go to '/contact'. But I he already in '/contact' and click in 'Contact' in menu, the page reload.
It's possible to do this?
What I'm trying:
<Link onClick={this.handleClick} to="contact">Contact</link>
handleClick(){
var currentRoute = 'React-Route path';
var linkRoute = 'link path';
if (currentRoute === linkRoute)
location.reload();
} else {
//do default transition
}
}
But I don't figure what I need to declare in 'currentRoute' and 'linkRoute'. :(

You shouldn't reload the page. Thats a really bad idea. Instead disable the link like this:
if you are on the home page your links would look like this
home
contact
about
Then in your handleClick() function you can just do this.
handleClick(e){
e.preventDefault();
var disabled = $(e.currentTarget).data('disabled');
if (!disabled){
//do redirect
}
}
Basically have a data attribute on the link that specifies if it is disabled or not (only disabled if its on the current page) and then only redirect if its on a different page
Reloading the page on the exact same page will cause you to lose all state and process that the user has done, which doesn't need to happen. It also reduces traffic on your server for a new page load (aka any data you need to load on the page load you don't have to do again).

You can use window.location.href to get the current URL. Then you can do your comparison.

Related

Gatsby How do I reset the app on a site reload

I am creating a react/Gatsby website and am trying to get the navigation working an need some guidance
So basically I have a site on a domain like: https//mysite.com
When navigating in the site my route gets added to the domain, like so: https//mysite.com/page1,
https//mysite.com/page2 etc.
When I refresh the browser I want the site to reload the website to its origional state, ie, https//mysite.com.
When I do reload from /page2, for example, the site seems to remember the last position. So on a reload I still have https//mysite.com/page2 in the address bar, whereas I want the site to go to the home page.
Is this possible?
Thanks
See this question for how to detect a page reload (such as pressing F5). The second most upvoted answer recommends this code for detecting the refresh and triggering another function:
componentDidMount() {
window.onbeforeunload = function() {
this.onUnload();
return "";
}.bind(this);
}
Gatsby uses #reach/router under the hood. So use Gatsby Link to redirect to your root page:
import { navigate } from "gatsby"
componentDidMount() {
window.onbeforeunload = function() {
this.onUnload();
return "";
}.bind(this);
navigate("/"); // redirect to your root page here
}
The user will be able to go back to the previous page. If you don't want this you replace the history like this:
navigate("/", { replace: true });

How to prevent user from going back in react-router-dom?

I'm using react-router-dom for routing in my reactjs app. And i want to prevent user from going back after login i.e i don't want to user go back again on login screen when he hit back button on browser after login.
Using componentDidUpdate method of React page lifecycle, you can handled or disabled go back functionality in browser. basically componentDidUpdate method will call automatocally when component got updated. so once your component is updated you can prevent to go back as below.
componentDidUpdate() {
window.history.pushState(null, document.title, window.location.href);
window.addEventListener('popstate', function(event) {
window.history.pushState(null, document.title, window.location.href);
});
}
This will prevent to user go back and uses the current page as a refernce for history object . so incase of user even click on back button of browser, they can not go backword in the last page.
You can checkout this codesandbox example may be that will help you or someone who is looking for the same.In this we can prevent the user to go back to previous page,For more detail checkout this medium article. here is small part of the code
componentDidMount() {
const { history } = this.props;
window.addEventListener("popstate", () => {
history.go(1);
});
}
for full working example click on this link.
Are you using redux? other wise you can add something on your render that checks if the user is already logged in it redirects him back to the page he was like:
import { Redirect } from 'react-router'
render(){
//I store my user JWT on this.props.currentUser redux state
this.props.currentUser && <Redirect to={'whatever page you want'} />
//OR you can also, if you have history, history.goBack()
So instead of forbidding going back, you forbid the user to ever going to the login page while logged in, it redirects him somewhere or back to where he was
window.addEventListener('popstate', function(event) {
});
use this function this will read your browser back button click event and after that whatever condition you want you can apply

Browser back button going to application page after logout

I have logout button in my angularjs(1.5) application. On click of it calling the login page url.After logout, when i click the browser back button again it is going to my application page instead of login page.
$scope.logOutUser = function () {
$window.location.href = "logoutURL";
}
Can anyone suggest how to implement this in angularjs?
Use $location service's .replace() method
$scope.logOutUser = function () {
$window.location.href = "logoutURL";
$location.replace()
}
Please take this my old post abut the back button issue : How to detect if a user clicks browser back button in Angularjs
You may may need that logic like
$scope.$on('$routeChangeStart', function (scope, next, current) {
if (next.$$route.controller != "Your dashboard Controller Name") {// please be mine dash board controller is your home page after login
// Show here for your model, and do what you need**
$window.location.href = "logoutURL";
}
});
But if you did logout in dashboard page then it would be an issue. At this time you need to maintain a flag with ng-Storage for the user is currently authenticate or not.

How to change the URL without reloading the page when back button is clicked in angularjs?

I am using angularjs for my app. It contains a newsfeed. If user needs to view the particular news, he has to click on that particular news and it will redirect to that news. And after viewing the particular news, if user wants to go back to news feed(previous page), he has to click on the browser back button. So, in this case, if user clicks on the browser back button, the newsfeed page is reloading again. But, I dont want like this. I want to disable the reload and take the user to the place where he was before. I browsed a lot on this issue, but there was no absolute solution given. Please, help me out.
When you go back, previous route will be triggered and data will be reloaded. If you want to prevent reloading, place a service in between and cache the data.
$routeProvider.
when('/loadFeeds',{
controller:'LoadFeedCtrl',
templateUrl:'pages/feeds.html',
resolve:{
initData : function(FeedService){
return $q.all(
{
data: FeedService.load()
}
);
}
}
})
And in your FeedService, instead of making http call try to see the data is already available
.service('FeedService',function($q,$timeoute){
this.feeds=[];
this.load = function(){
var deferred = $q.defer();
$timeout(function(){
if(feeds.length===0){
this.feeds.push({title:'First','id':1})
this.feeds.push({title:'Second','id':2})
this.feeds.push({title:'Third','id':3})
this.feeds.push({title:'Fourth','id':4})
}
deferred.resolve(this.feeds);
},2000);
return deferred.promise;
};
})
The timeout service could be replaced with $http or $resource. I used the timeout to simulate the delay
you can take an anchor link and on click event of anchor call this
javascript function
window.window.history.back();
here is the html code for it
<input type="button" id="alnkBack" onclick="window.window.history.back();" value="Back" class="button" />

How to maintain state of page with tabs on browser refresh

In ExtJs, what is the best way to handle Browser refresh?
Say, I've a page with two tabs A and B
and the token when tab A is active is #mytoken/:someidforA
and the token when tab B is actibe is #mytoken/:someidforB
How do we ensure that the page stays in the same tab when we refresh the browser?
I'm doing something like this using Router in ExtJs5
window.onbeforeunload = function() {
token = // get history token
MyApp.getController('Main').redirectTo(token);
}
and inside the ViewControllers -
routes: {
"#mytoken/:someidforA" : "loadA",
"#mytoken/:someidforB" : "loadB"
}
Is this a good way to do it?
I would personally use the documented routes
Example:
Ext.define('MyApp.view.main.MainController', {
extend : 'Ext.app.ViewController',
routes : {
'user/:id' : 'onUser'
},
onUser : function(id) {
//...
}
});
You can also define the default route with the defaultToken property:
defaultToken : 'home'
It seems like you are already using some of these features. If the URL is something like example.com/#user/4 then on page refresh the application can handle this route as it previously did and show the same page/section.
To restore all the tabs that were open before refresh you'd probably have to look at using something like localstorage to keep state across page refreshes

Resources