Home > Blockchain >  How to conditionally render the page with use effect?
How to conditionally render the page with use effect?

Time:02-26

I am fetching some data to render to the page. If user/data isn't available I'm trying to render a component that states the user's account is inactive/pending. My problem I'm rendering the pending component while waiting for the data to load and the transition just looks a bit awkward. How would I go about setting it so that nothing is displayed until the data fetching process has been resolved

My code:


  const { user } = useAuth0();
  const [records, setRecords] = useState([]);
  const [hasLoaded, setHasLoaded] = useState();

  useEffect(() => {
    fetchData();
  }, [records]);

  const fetchData = () => {
    fetch(recordapi   "/record")
      .then((response) => response.json())
      .then((data) => {
        setRecords(data);
        setHasLoaded(true);
      })
      .catch((error) => {
        console.log(error);
      });
  };
  let userProfile = records.find((x) => x.email === user.email);
  return (
    <>{userProfile && hasLoaded ? <AdminDashboard /> : <PendingAccount />}</>
  );
}

export default AdminDashboardPage;

CodePudding user response:

Sounds like you need something like

return userProfile
  // The API has finished and the email is found
  ? <AdminDashboard />
  // Otherwise, show PendingAccount only after the API has finished and no email is found
  : hasLoaded && <AdminDashboard />;

But you may be able to remove the hasLoaded state completely and instead check records.length -

return userProfile
  // The API has finished and the email is found
  ? <AdminDashboard />
  // Otherwise, show PendingAccount only after the API has finished and no email is found
  : records.length > 0 && <AdminDashboard />;

On a completely different note, if this code is running on the client side, it sounds like you're sending the data for all admin users to the client, then checking whether this particular client is a member - this process may well allow the client to collect the user data of admins, including emails, which is probably undesirable. If this is a concern, you might consider doing the validation on the server instead.

CodePudding user response:

In this scenario, you can use the spinner till you get the data using react-loader-spinner.

import Loader from 'react-loader-spinner';
hasLoaded ? <div>
                <Loader type="Rings" color="#00BFFF" height={70} width={70} timeout={10000}/>
</div>: your code.`
  • Related