Search code examples
javascriptreactjsjsxrender

React component not rendering after then() succeeds


I want to render some JSX based on a condition, but it is not happenning. Below is my code -

chkAccess().then((result) => {
    console.log(result)
    if(result) {
        alert("Access Granted")
        return (
            <div className='login_container p-5 m-5 bg-dark'>
            <h1 className='text-center p-3'>You are seeing this page because you are a Manager</h1>
            </div>
        )
    }
    alert("Access Denied")
    return(<Access_denied />)

The JSX returned is not getting rendered. Why is it so and how I can i fix it?

I expect the returned code to be rendered, but It did not happen.


Solution

  • From what I can see your implementation is wrong. If you need to first check the user's access you should display loading and after checking the permission set the state based on the permission the user has and then render the JSX based on that state. If you don't want the user to see a loading spinner, You can use the Server side and before rendering the component you check

    const [hasAccess, setHasAccess] = useState(null);
    
      useEffect(() => {
        chkAccess().then((result) => {
          setHasAccess(!!result);
        });
      }, []);
    
      if (hasAccess === null) return <Loading />;
    
      if (!hasAccess) {
        alert("Access Denied");
        return <Access_denied />;
      }
    
      if (hasAccess)
        return (
          <div className="login_container p-5 m-5 bg-dark">
            <h1 className="text-center p-3">
              You are seeing this page because you are a Manager
            </h1>
          </div>
        );