Created
May 1, 2020 03:58
-
-
Save crrmacarse/511df7e662626f3a47d9cc444a8c90c6 to your computer and use it in GitHub Desktop.
Session handling with SPA
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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