I'm building a React app which requires authentification to use an API. So I keep the user token in my React context. Everything works fine as long as the user stay in the same session but, of course, whenever I open a new tab or refresh the current one, the context is lost. So I created a component that either stocks the token in localStorage (if there is a token) or retrieve said token from the localStorage.
I thought I had it figured out but... it doesn't work as expected. When I open a new tab, I am redirected to the login page (which is expected when there is no token).
I've checked what happens with some console logs and :
Here is my token handler component (called directly in App.jsx) :
import { useContext, useEffect } from "react";
import { DisplayContext } from "../context/DisplayContext";
export default function TokenHandler() {
const {
setCurrentUser,
userToken,
setUserToken,
setTokenLimit,
setUserRole,
} = useContext(DisplayContext);
const retrievingToken = () => {
let stockDate = new Date();
if (localStorage.getItem("mddTheme") && !userToken) {
const stockToken = localStorage.getItem("mddTheme");
if (stockDate.getTime() < stockToken.exp) {
setUserToken(localStorage.getItem("mddTheme"));
setCurrentUser(stockToken.sub);
setTokenLimit(stockToken.exp);
setUserRole(stockToken.aud);
} else {
localStorage.removeItem("mddTheme");
}
}
console.log(
"retrieving token : ",
userToken,
localStorage.getItem("mddTheme")
);
};
const stockingToken = () => {
if (
userToken &&
(!localStorage.getItem("mddTheme") ||
localStorage.getItem("mddTheme") !== userToken)
) {
localStorage.setItem("mddTheme", userToken);
}
console.log(
"stocking token : ",
userToken,
localStorage.getItem("mddTheme")
);
};
useEffect(() => {
console.log(
"token handler : ",
userToken,
localStorage.getItem("mddTheme")
);
// if (userToken !== "") {
stockingToken();
// } else {
retrievingToken();
// }
}, [userToken]);
return <></>;
}
Any idea why a new tab can't read the storage on opening ?