admin管理员组

文章数量:1434916

I use the axios post to request to the back-end if the user have access to the application. The problem is the axios returns undefined and then true or false . Have a private Route to manage what to do in case returns true or false (in this case undefined = false) ,is axios the problem or is there some other way? like wait until returns true or false

IsLogin.jsx

import React from 'react'
const axios = require('axios');
export const AuthContext = React.createContext({})

export default function Islogin({ children }) {
   const isAuthenticated =()=>{
       try{
            axios.post('/api/auth').then(response => {
               var res = response.data.result;
               console.log(res)
               return res
           })
       } catch (error) {
           console.error(error);
           return false
       }

   }
  
   var auth = isAuthenticated()
   console.log(auth);
   return (
       <AuthContext.Provider value={{auth}}>
           {children}
       </AuthContext.Provider>
   )
}

privateRoute.js

import React, { useContext } from 'react';
import { Route, Redirect } from 'react-router-dom';
import  {AuthContext}  from '../utils/IsLogin';

const PrivateRoute = ({ponent: Component, ...rest}) => {

   const {isAuthenticated}  = useContext(AuthContext)
   
   return (

       // Show the ponent only when the user is logged in
       // Otherwise, redirect the user to /unauth page
       <Route {...rest} render={props => (
           isAuthenticated ?
               <Component {...props} />
           : <Redirect to="/unauth" />
       )} />
   );
};
export default PrivateRoute; 

app.js

class App extends Component {
  render() {
  return (
    <>
    <BrowserRouter>
    <Islogin>
      <Header/>
    <Banner/>
     <Switch>
      <PrivateRoute exact path="/index" ponent={Landing} />
     <PrivateRoute path="/upload" ponent={Upload} exact />
     <PublicRoute restricted={false} path="/unauth" ponent={Unauthorized} exact  />
    </Switch>
    </Islogin>
    </BrowserRouter>
  
    </>
  );
}
}

I use the axios post to request to the back-end if the user have access to the application. The problem is the axios returns undefined and then true or false . Have a private Route to manage what to do in case returns true or false (in this case undefined = false) ,is axios the problem or is there some other way? like wait until returns true or false

IsLogin.jsx

import React from 'react'
const axios = require('axios');
export const AuthContext = React.createContext({})

export default function Islogin({ children }) {
   const isAuthenticated =()=>{
       try{
            axios.post('/api/auth').then(response => {
               var res = response.data.result;
               console.log(res)
               return res
           })
       } catch (error) {
           console.error(error);
           return false
       }

   }
  
   var auth = isAuthenticated()
   console.log(auth);
   return (
       <AuthContext.Provider value={{auth}}>
           {children}
       </AuthContext.Provider>
   )
}

privateRoute.js

import React, { useContext } from 'react';
import { Route, Redirect } from 'react-router-dom';
import  {AuthContext}  from '../utils/IsLogin';

const PrivateRoute = ({ponent: Component, ...rest}) => {

   const {isAuthenticated}  = useContext(AuthContext)
   
   return (

       // Show the ponent only when the user is logged in
       // Otherwise, redirect the user to /unauth page
       <Route {...rest} render={props => (
           isAuthenticated ?
               <Component {...props} />
           : <Redirect to="/unauth" />
       )} />
   );
};
export default PrivateRoute; 

app.js

class App extends Component {
  render() {
  return (
    <>
    <BrowserRouter>
    <Islogin>
      <Header/>
    <Banner/>
     <Switch>
      <PrivateRoute exact path="/index" ponent={Landing} />
     <PrivateRoute path="/upload" ponent={Upload} exact />
     <PublicRoute restricted={false} path="/unauth" ponent={Unauthorized} exact  />
    </Switch>
    </Islogin>
    </BrowserRouter>
  
    </>
  );
}
}
Share Improve this question asked Aug 13, 2020 at 18:51 Enzo ZalazarEnzo Zalazar 131 gold badge1 silver badge5 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 1

You don't want to return anything in your post request. You should be updating your context store

const isAuthenticated = () => {
    try {
        axios.post('/api/auth').then(response => {
            var res = response.data.result;
            console.log(res)
            // update your context here instead of returning
            return res
        })
    } catch (error) {
        console.error(error);
        return false
    }
}

In your private route, have a ponentDidUpdate style useEffect hook to check for changes in authentication status and update an internal flag on an as-needed basis

const PrivateRoute = ({ ponent: Component, ...rest }) => {
    const { isAuthenticated } = useContext(AuthContext)
    const [validCredentials, setValidCredentials] = React.useState(false)

    React.useEffect(() => {
        if (typeof isAuthenticated === 'boolean') {
            setValidCredentials(isAuthenticated)
        }
    }, [isAuthenticated])


    return (

        // Show the ponent only when the user is logged in
        // Otherwise, redirect the user to /unauth page
        <Route {...rest} render={props => (
            validCredentials ?
                <Component {...props} />
                : <Redirect to="/unauth" />
        )} />
    );
};

本文标签: javascriptREACThow can wait until api call finish to load a pathStack Overflow