javascript - running functions one after other in react - Stack Overflow

admin2025-04-19  2

after setState, i want to call service.logout(), then Auth.logout() function,

 ponentWillMount() {
    if (!(this.Auth.loggedIn())){
      this.props.history.replace('/login');
    } else {
      this.setState({token : this.Auth.getToken()}).then(service.logout(this.state.token)).then( this.Auth.logout())
      // console.log('token',this.state.token)

    }
  }

but im getting error like this,

 TypeError: Cannot read property 'then' of undefined
LogoutponentWillMount
src/ponents/auth/Logout.js:20
  17 | if (!(this.Auth.loggedIn())){
  18 |   this.props.history.replace('/login');
  19 | } else {
> 20 |   this.setState({token : this.Auth.getToken()}).then(service.logout(this.state.token)).then( this.Auth.logout())
  21 |   // console.log('token',this.state.token)
  22 |  
  23 | }

after setState, i want to call service.logout(), then Auth.logout() function,

 ponentWillMount() {
    if (!(this.Auth.loggedIn())){
      this.props.history.replace('/login');
    } else {
      this.setState({token : this.Auth.getToken()}).then(service.logout(this.state.token)).then( this.Auth.logout())
      // console.log('token',this.state.token)

    }
  }

but im getting error like this,

 TypeError: Cannot read property 'then' of undefined
Logout.ponentWillMount
src/ponents/auth/Logout.js:20
  17 | if (!(this.Auth.loggedIn())){
  18 |   this.props.history.replace('/login');
  19 | } else {
> 20 |   this.setState({token : this.Auth.getToken()}).then(service.logout(this.state.token)).then( this.Auth.logout())
  21 |   // console.log('token',this.state.token)
  22 |  
  23 | }
Share Improve this question asked May 3, 2018 at 6:41 LogaKrishnanLogaKrishnan 5012 gold badges9 silver badges25 bronze badges 6
  • What is this.Auth ? Have you imported the same in your file ? Could you please share you code. – Rohan Kangale Commented May 3, 2018 at 6:48
  • @rohankangale import AuthService from './AuthService', in then construcor i have added this line, this.Auth = new AuthService(); – LogaKrishnan Commented May 3, 2018 at 6:50
  • I will suggest you to move this code to ponentDidMount(), instead of ponentWillMount(). Also, do check whether you are getting the response for this.Auth.loggedIn(). – Rohan Kangale Commented May 3, 2018 at 6:53
  • @rohankangale` this.Auth.loggedIn()` works as, if token not present it redirects url to /login – LogaKrishnan Commented May 3, 2018 at 6:55
  • Ok. If your service function is working fine, then move your code to ponentDidMount(). – Rohan Kangale Commented May 3, 2018 at 6:56
 |  Show 1 more ment

4 Answers 4

Reset to default 3

from https://reactjs/docs/

so i think this would solve your problem

      this.setState({token : this.Auth.getToken()} , async () => {
       await service.logout(this.state.token) 
       await this.Auth.logout()
      });
      
      
      

this.setState does not return "Promise" and that's why it is not proper to use "then" method to chain the operations. ref.

If your "service.logout(..)" returns Promise than probably following one will work.

ponentWillMount() {
if (!(this.Auth.loggedIn())){
  this.props.history.replace('/login');
} else {
  const authToken = this.Auth.getToken();
  this.setState({token : authToken }, () => { 
       service.logout(authToken).then( this.Auth.logout());
  });
}

}

  1. First of all, don't use ponentWillMount instead use ponentDidMount. ponentWillMount is going to deprecate in react17.

  2. setState don't return a promise, rather you can use a callback which will execute after state has been set.

  3. In below example I call logout function in call back which returns a promise. There you can use .then() because that function returns a promise with help of async await

  4. You can also direct make callback function to a async callback function using async syntax.

  ponentDidMount() {
    if (false){
      this.props.history.replace('/login');
    } else {
      this.setState({token : 'one'}, () => {
        this.logout(this.state.token).then(() => {
          // Do whatever you want
          console.log('three');
        });
      });
    }
  }

 logout = async (token) => {
     const a = new Promise((resolve, reject) => {
          setTimeout(() => { console.log('two'); return resolve("done!"); }, 1000)
     });

     return await a;
  }

To check the working example click here

Sorry, I don't know react, but I know Angular. If the service.logout() returns an Observable, then shouldn't you bind .then() method with it return value, like this?

this.setState({token : this.Auth.getToken()}).then(service.logout(this.state.token).then( this.Auth.logout()))
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745041820a281589.html

最新回复(0)