I am making a create-react-app
that stores an access token within document.cookie
to handle login / accessing protected routes.
My main component, App.js
has a function isLoggedIn()
:
async isLoggedIn() {
if (document.cookie !== '') {
// Check for existence of `token` cookie
let cookies = parseCookies(document.cookie);
if (cookies.token) {
try {
let payload = await BackendService.verifyToken(cookies.token);
this.setState({
'name': payload.name,
'email': payload.email
});
return payload.valid || false;
} catch (err) {
return false;
}
} else {
console.log('No token cookie found.')
return false;
}
}
return false;
}
I pass this function as a prop to children to allow them to check login status:
<TopBar isLoggedIn={this.isLoggedIn} />
Within TopBar is where I conditionally render based on isLoggedIn()
:
{ this.props.isLoggedIn() &&
<li className="nav-item">Welcome <a href="#account">{this.props.name}</a></li>
}
{ !this.props.isLoggedIn() &&
<li className="navItem"><a href="#login" onClick={this.showModal}>Sign In</a></li>
}
However, when document.cookie
is empty (deleted cookies through Application tab of Dev Tools), Welcome
is rendered rather than the Sign In
.
If I try to log the value of this.props.isLoggedIn()
from within TopBar
, instead of a boolean being printed, a Promise is printed? Which doesn't make sense to me. Sure async
keyword on isLoggedIn()
indicates a function could be returned, but I am explicitly returning a boolean at each stage of the control flow, so I am unsure how a promise is ever involved.
The only way I could see a promise being returned is because of the BackendService.verifyToken()
function, but that is using await
anyways and so shouldn't return a promise. Also a promise shouldn't be returned anyways if I immediately exit the function with false
, right?
I have looked at similar questions, however like I said above, using the await
keyword should be enough to return a value and not a promise.