Home > Net >  React component not rendering after then() succeeds
React component not rendering after then() succeeds

Time:11-14

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.

CodePudding user response:

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>
    );

CodePudding user response:

You should use a state to keep track of your async call result, then render different elements based on the current state.

Here is an example based on the implementation:

import { useEffect, useState } from "react";

export default function App() {
  const [hasAccess, setHasAccess] = useState(false);
  const [loading, setLoading] = useState(false);

  // Here we mock access check.
  const chkAccess = async () => Promise.resolve(() => true);

  useEffect(() => {
    setLoading(true);
    const timer = setTimeout(() => {
      setHasAccess(chkAccess());
      setLoading(false);
    }, 1000);
    return () => clearTimeout(timer);
  }, []);

  const renderContent = () => {
    if (loading) {
      return "Loading...";
    }
    if (!hasAccess) {
      return "Access Denied";
    }
    return "Authenticated";
  };

  return <div className="App">{renderContent()}</div>;
}

Edit 74427705

  • Related