最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - REACT - how can wait until api call finish to load a path? - Stack Overflow

matteradmin5PV0评论

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" />
        )} />
    );
};
Post a comment

comment list (0)

  1. No comments so far