User & Authorization
Another data that you can query using hooks is the user's data.
In TVLK5, user data is only fetched in client-side except in 1 condition (and even then, you can't access it inside component in server environment). The reason for this behavior is we want our HTML result to be cacheable across multiple users. You need to take this behavior into account when designing a UI.
The useUser hook
We provide the useUser hook that return value depending on session state.
Not logged in state
If user is not logged in, you'll get Guest object which contains loggedIn property set to false and authorizationLevel property in case you want to specific logic depending on that.
type UserAuthorizationLevel = 100 | 200 | 300 | 400 | 500;
type Guest = {
loggedIn: false;
authorizationLevel: UserAuthorizationLevel;
};
type UserData = {
loggedIn: true;
authorizationLevel: UserAuthorizationLevel;
clientId: string;
sessionId: string;
id: string;
name: string;
username: string;
email: string;
};
Logged in state
When user is logged in, you get full UserData object that also contains loggedIn and authorizationLevel property. To access these property, however, you always need to handle the non-logged-in scenario first. Failing to do so will makes our type system throw an error.
import { Text } from '@traveloka/web-components';
import { useUser } from '@traveloka/core';
function Component() {
const user = useUser();
if (!user) {
// user data is not fetched yet
return null;
}
if (!user.loggedIn) {
// guest
return <Text>{'Please log-in'}</Text>;
}
return user.name;
}
Local storage cache
This is considered implementation detail. Whenever possible, please just use the data from the useUser hook.
We cache user session data inside the localStorage via loadUserSession and clearUserSession helpers (these allow you to access the internally cached values).
Caching user session data inside the localStorage allows the useUser hook to return (possibily stale) data first before revalidating with the backend (to reduce perceived latency).
Clearing partner API tokens
When users log out, you should also clear partner API tokens (e.g., TravelokaPay tokens) stored in both localStorage and cookies using the clearPartnerAPISession function:
import { clearUserSession, clearPartnerAPISession } from '@traveloka/core';
function handleLogout() {
clearUserSession();
clearPartnerAPISession();
// Redirect to login or home page
}
This ensures that when a user logs out, all partner API authentication data is properly cleared from storage.
Low-level functions
If, fore some reason you need to interact with the internal values on useUser, you access the state/reducer via the useAuth hook.
export default function useReauthenticationFlow() {
// `userState` is from `useUserState()`
// `userDispatch` is from `useUserDispatch()`
const [userState, userDispatch] = useAuth();
}