Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Async Route Element Return in React JS

Getting Error: Guard(…): Nothing was returned from render. This usually means a return statement is missing.

I want to call the API in my guard component before returning the element to Route Element to check if the logged in user have access to specific route or not.

For that, I have implemented a guard. Here’s the route file code.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

export default function Router() {
    return (
        <Routes>
            <Route path="organizations">
                <Route path="list" element={<Guard><ListOrganization /></Guard>} />
        </Routes >
    );
}

Guard component code

const Guard = (props) => {
    fetch('https://apiToCheckPermission.com')
    .then(response => {
        if (response.isPermission) {
            return props.children;
        }
    })
};

export default Guard;

It’s kind of a thing that, I want to implement async route element. But React is throwing error if I don’t immediately return the element from Guard.

Can anyone please tell How to solve this error?

>Solution :

Try to define a state to handle the permission and useEffect to load the data:

const Guard = (props) => {
  const [hasPermission, setHasPermission] = useState(false);

  useEffect(async () => {
    const response = await fetch('https://apiToCheckPermission.com');
    setHasPermission(response.isPermission);
  }, []);

  if (!hasPermission) return <>Unauthorized</>;

  return props.children;
};

export default Guard;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading