skip to Main Content

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


  1. I suggest for you to add a state isloading:

    export default function Component() {
      const [isLoading,SetIsLoading] = useState(false);
    
      useEffect(() => {
        SetIsLoading(false)
        axios
          .post(`http://${process.env.REACT_APP_RUN}:3001/api/token/status`, {
            token,
          })
          .then((response) => {
            setvalidtoken(response.data);
            setIsLoading(true)
          });
      }, []);
    if(isLoading){
      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>;
      }
    }
    }
    
    Login or Signup to reply.
  2. 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 to true and is set to false when the API call finishes and use that to show a loading placeholder, or you could maybe just return early if validtoken is not yet set (assuming that it is undefined until it is set in the API call).

    if (!validtoken) return <p>Loading...</p>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search