I created a separate node.js restful API for checking if the user token is valid. I did this for my react protected routes, even though most of my endpoints already checks the user token.
My redux Thunk:
const verifyToken = () => {
return async (dispatch: Dispatch) => {
await axios
.get("http://localhost:9999/authenticate", {
headers: { Authorization: `Bearer ${localStorage.getItem("token")}` },
})
.then(async (resp) => {
const { message } = await resp.data;
console.log(message);
if (message === "verified") dispatch({ type: "signIn-success" });
})
.catch((err) => {
console.log(err);
dispatch({ type: "logout-user" });
});
};
};
Protected Route:
const ProtectedRoute: FC<{ children: ReactNode; path: string }> = ({
children,
path,
}) => {
const dispatch = useDispatch();
dispatch(verifyToken()); //dispatch thunk
const status = useSelector((store: RootStore) => store.status)
return status && status === "loggedOut" ? (
<Redirect to="/" />
) : (
<Route path={path} render={() => <>{children}</>} />
);
};
The problem is that it takes time to dispatch my thunk, so it redirects to "/" even though the user token checking hasn't finished.
So what happens is, the value of status is "loggedOut" at first then my thunk will check if the token is valid. If it is, status becomes "loggedIn", but its too late because it already redirected to "/"