Home > Software design >  Page is loaded before API Call on React
Page is loaded before API Call on React

Time:01-15

I'm new on React, I'm trying to create a ProtectedRoute which only load if i receive true from a API Call, otherwise will be redirected to a different page. The issue is that the page load first and then the API is called.

  1. The Blue part is the call to the API to obtain the "hasAccess" variable which can be true or false
  2. the details of the routes I have and the ProtectedRoute one.
  3. When I set the values of auth manually to True or false it works as expected but when I set the value of auth={hasAccess} then it always return false because the API is called after the page is loaded. code snippet screenshot

CodePudding user response:

"then it always return false because the API is called after the page is loaded." - It is not because the API is called after the page is loaded, since the API can't even be called before as the call in itself is part of the page (considering it is a single-page application).

If you want to prevent protected from being rendered before the API call is returned, then you should render it conditionally:

<ProtectedRoute path="/protected-path" component={hasAccess ? protected : undefined} />

or

{hasAccess && <ProtectedRoute path="/protected-path" component={protected} />}

CodePudding user response:

const [hasAccess,setAccess] = useState(false)l

// set Access inside the useEffect

<ProtectedRoute path='/protected_path' component={hasAccess? Protected:''}>
  •  Tags:  
  • Related