Search code examples
reactjsrouter

React PrivateRoute not returning boolean, but promise


I'm creating a privateRoute file that checks for the user token in the server side and checks if it is still valid. the fetch function should return true or false depending if it is valid or not, and when this value is checked, decide whether if it goes to the outlet or ot the accessrestricted page.

const tokenString = localStorage.getItem('token');

const PrivateRoutes = () => {
 
  const handleSubmit = async e => {
      const res = await Rolcheck(tokenString);
      return res;
  }
  const auth = handleSubmit();

  return (auth ? <Outlet/> : <Restricted/>)

}

export default PrivateRoutes

Note that Rolcheck (named after what I will do in the future with it) is an async function that sends the token to the db and compares it there, then returns true or false depending on this.

After a console.log(), I can get the right expected boolean option if I check inside handleSubmit, however, the const auth gets a promise. I'm not sure If this is messed due to async/await.


Solution

  • const tokenString = localStorage.getItem('token');
    
    const PrivateRoutes = () => {
      const [state,setState] = useState(undefined)
    
      useEffect(()=>{
         Rolcheck(tokenString).then(setState).catch(()=>setState(false))
      },[])
     
     if(state === undefined)
       return <React.Fragment/>
    
      return (auth ? <Outlet/> : <Restricted/>)
    }
    
    export default PrivateRoutes