Previously I was using local storage to store the tokens so that they can be shared among all the tabs, but I needed a requirement to delete the tokens when the user closes all the tabs or the entire browser, so I switched to session storage to save the token and used storage event listener to share it among all the tabs, The functionality is working as expected, but I could see an edge case here is, when I login successfully, and opens a new tab and try to open the application, it redirects to login page because when the page renders at first it won't have token in session storage, after few seconds only we will get the token from the logged-in tab.
My Requirement is - How can I get the data from the already opened tab session storage and store them in the newly opened tab before the page gets rendered?
According to the code, it redirects to the login page since it doesn't have tokens during page render, but after that, I can see the tokens in session storage, so how can I solve this issue, so that on-page render itself I can have the token and redirect to home page.
Here is the code,
App.js
function App(){
return(
//All other route codes
<Route exact render={() => getUserToken() ? <Redirect to="/home"/> : <Redirect to="/login"/> } />
)
}
service.js
export const getUserToken = () => {
const token = sessionStorage.getItem("token");
return token
}
apps.component.js
// To trigger the storage event listener on every page render
useEffect(() => {
localStorage.setItem("REQUEST_TOKEN",Date.now().toString());
localStorage.removeItem("REQUEST_TOKEN")
},[])
// To get the token from opened tab and store them in newly opened tab session storage
useEffect(() => {
window.addEventListener('storage', () => {
const tokenCreds = sessionStorage.getItem("token")
if(event.key === "REQUEST_TOKEN" && tokenCreds){
sessionStorage.setItem("token",event.newValue)
}
})
},[])
Is there any way to get the token before the new tab renders completely so that it can redirect to the home page?
Thanks in advance!!!