i have a timing problem in react.js
i have a component that checks the user valid.token and user type and if is admin display content and if is not displays " you don’t have premission "
but when the user is a admin at first component shows " you don’t have permission" and immediately displays the content
I think its an asynchronous problem because it takes some time to get user type from backend, how to fix this in react.js
my component looks like this:
export default function Component() {
useEffect(() => {
axios
.post(`http://${process.env.REACT_APP_RUN}:3001/api/token/status`, {
token,
})
.then((response) => {
setvalidtoken(response.data);
});
}, []);
if (!token || validtoken.valid === "false") {
window.location.replace(`http://${process.env.REACT_APP_RUN}:3000/login`);
} else if (validtoken.type !== "admin") {
return (
<>
<Navbar />
<div className="premission-denied-holder">
<div className="premission-denied-ithed">
<h6 className="text-premisson">you dont have premission</h6>
</div>
</div>
</>
);
} else {
return <h1>some content here</h1>;
}
}
I tried to change the sequence
2
Answers
I suggest for you to add a state isloading:
You need to track whether the API request is finished or not. You could either add a new piece of state called something like
isLoading
that defaults totrue
and is set tofalse
when the API call finishes and use that to show a loading placeholder, or you could maybe just return early ifvalidtoken
is not yet set (assuming that it is undefined until it is set in the API call).