Conditional Routing - Async

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP


Conditional Routing - Async



I wanted to make a GET request to my server to verify if the user is authenticated or not, basically a true or false function.
but it ended up being more complicated than that.


GET


true or false



as i need an async,await function in order to get the response from the request i made.
SO, thats what i did. but after calling the function inside a regular sync function which is PrivateRoute it only logs that the promise is still pending.


async


await


response


request


sync


PrivateRoute


promise


pending



SO, i tried turning PrivateRoute into an async function. but react refused to render a [object promise].


PrivateRoute


async


[object promise]



ANY IDEA what to do?


const isAuthenticated = async () => {
try{
let isAuth = await axios.get('/auth')

console.log(isAuth.data)
if(Object.keys(isAuth.data).length > 0) return true
else return false

} catch(err) {
console.log(err)
}
}



const PrivateRoute = (route) => {
const authenticated = isAuthenticated() // returns a pending promise
console.log(authenticated)

return (
<Route path={route.path} render={() => {
if (authenticated) return <Profile_Tabs />
return <Redirect to='/' />
}} />
)
}

<PrivateRoute
path='/profile'
exact={true}
/>




1 Answer
1



You could make the PrivateRoute component stateful.


PrivateRoute


state = {
isAuthenticated: null,
}



You could then do


isAuthenticated().then(isAuthenticated => this.setState({ isAuthenticated }))



Your render function can then be updated to check the state and conditionally render.






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Visual Studio Code: How to configure includePath for better IntelliSense results

Spring cloud config client Could not locate PropertySource

Regex - How to capture all iterations of a repeating pattern?