Skip to content

Instantly share code, notes, and snippets.

@crrmacarse
Created May 1, 2020 03:58
Show Gist options
  • Save crrmacarse/511df7e662626f3a47d9cc444a8c90c6 to your computer and use it in GitHub Desktop.
Save crrmacarse/511df7e662626f3a47d9cc444a8c90c6 to your computer and use it in GitHub Desktop.
Session handling with SPA
/* eslint-disable no-empty, no-param-reassign */
import api from 'utils/api';
const LS_SESSION = 'hasSession';
export const startSession = () => window.localStorage.setItem(LS_SESSION, 'true');
export const resetSession = () => window.localStorage.removeItem(LS_SESSION);
export const hasSession = (): boolean => {
const val = Boolean(window.localStorage.getItem(LS_SESSION));
return val;
};
const checkSession = async (preloadedState: {} = {}) => {
try {
// Early out if session is non existent
if (!hasSession()) {
return preloadedState;
}
const { data: response } = await api.get('/auth/me');
const { data } = response;
if (data) {
preloadedState = {
auth: {
authenticated: true,
profile: { ...data.user, roles: data.roles },
},
};
}
} catch (error) { resetSession(); }
return preloadedState;
};
export default checkSession;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment