1👍
✅
AuthProvider
has a useEffect
hook that calls updateToken
on an interval that makes a POST request to update tokens, and when/if there’s a non-200 response status the logoutUser
function is called and resets some auth state and navigates to "/"
. This all occurs regardless of the user’s current authentication status.
You only want to call logoutUser
if the user is actually logged in. Because updateToken
is called from a closure you can use a React ref to cache the current username
state value to avoid including username
as a useEffect
dependency.
const [username, setUsername] = useState(() =>
localStorage.getItem("authTokens")
? jwt_decode(localStorage.getItem("authTokens"))
: null
);
// React ref to store cached username "auth" state
const usernameRef = React.useRef(username);
// side-effect to cache username state value
useEffect(() => {
usernameRef.current = username;
}, [username]);
const updateToken = async () => {
const response = await fetch(
"http://127.0.0.1:8000/api/token/refresh/",
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ refresh: authTokens?.refresh }),
}
);
let data = await response.json();
if (response.status === 200) {
setAuthTokens(data);
setUsername(jwt_decode(data.access));
localStorage.setItem("authTokens", JSON.stringify(data));
} else {
// If user is currently authenticated, log them out
if (usernameRef.current) {
logoutUser();
}
}
if (loading) {
setLoading(false);
}
};
Source:stackexchange.com