According to ionic’s blog piece on Lifecycle hooks, the ionViewCanEnter
:
ionViewCanEnter: Fired before entering into a view, allows you to control whether the view can be accessed or not (returning true or false).
According to the docs, ionViewCanEnter
:
Runs before the view can enter.
Point is, before a page is entered and displayed, the ionViewCanEnter
should be resolved to true or false.
In my case, that ain’t happening. There’s a Flash Of Unwanted Content (FOUC)
The behavior I experience is, the page Loads before the ionViewCanEnter
happens. See what I mean in this 15 seconds video. I reload the page several times. When you see the lag, it is hard to unsee again:
My setup:
cli packages: (/some/where/node_modules)
@ionic/cli-utils : 1.9.2
ionic (Ionic CLI) : 3.9.2
global packages:
Cordova CLI : 7.0.1
local packages:
@ionic/app-scripts : 2.1.3
Cordova Platforms : android 6.2.3 ios 4.4.0
Ionic Framework : ionic-angular 3.6.0
System:
Android SDK Tools : 26.0.2
Node : v7.10.1
npm : 4.2.0
OS : Linux 4.10
My code
This is the function in my Authentication service.
isLoggedIn() {
let token = localStorage.getItem('token');
if (token) {
return true;
}
return false;
}
Then I’m using the above in my ionViewCanEnter
hook in my component as so:
ionViewCanEnter() {
if(!this.auth.isLoggedIn()) {
this.navCtrl.setRoot(WelcomePage);
}
}
My rootpage in my app component is the HomePage
(localhost:8100/#/home). When user isn’t logged in, they should not see that page.
Yet, in the video above, they see that page, because ionViewCanEnter
isn’t running on time.
This looks a lot more like a bug to me. Because I think nothing should come up UNTIL the hook resolves FIRST. In this case, the page resolved, before the hook kicked in, causing the FOUC.
PS: Before you jump to saying the front-end auth checks is baseless and auth checks should be done server-side, guess what. All my server-side checks are in place. The front-end tweaks for aesthestics sake. You don’t want user to enter long piece of text, only to tell the user after posting: “You’re not logged in”.