简体   繁体   中英

How to make axios call one after the other in React

Ho to call axios after execution of one event call another axios to get the latest status

onHandleDeactivate I want deactivate particular ID from UI, and after successfully deactivated I have to get the latest status for that id like 'deactivated' to get that I need to call /get API.

Note: I don't want reload/refresh the page to get the status for that id. But I can make axios /get call to get the latest status.

How can we achieve this?

  1. First call /deactivate Axios
  2. and then call /get to get the latest status for that Id

Right now with the below code it's not deactivating it's just calling /get axios. not the /deactivate

onHandleDeactivate = () => {
    let payLoad = {
      "Id": this.state.Id,      
    };
    axios.post('/deactivate', payLoad).then((response) => {
      this.closeDeactivateModal()
      this.setState({ successMessage: `Deactivated successfully.` });    
    }).catch(error => {
      this.setState({ errorMessage: error.message })
    }),
    axios.get('/get').then((response) => {
       this.setState({ result: response });
    }).catch((error) => {
      this.setState({ message: error.message}) 
    })
  }

you can use async await for that, or move your second request into then({...})

please read async await reference

this one example using async await

onHandleDeactivate = async () => {
  let payLoad = {
    Id: this.state.Id,
  }
  try {

    // first call
    let response = await axios.post('/deactivate', payLoad)
    this.closeDeactivateModal()
    this.setState({ successMessage: `Deactivated successfully.` })

    // second call
    try {
      let result = await axios.get('/get')
      this.setState({ result: result })
    } catch (error) {
      this.setState({ message: error.message })
    }

  } catch (error) {
    this.setState({ errorMessage: error.message })
  }
}

You could make you call in another .then in order to wait for the first call.

   onHandleDeactivate = () => {
        let payLoad = {
          "Id": this.state.Id,      
        };
        axios.post('/deactivate', payLoad).then((response) => {
          this.closeDeactivateModal()
          this.setState({ successMessage: `Deactivated successfully.` });    
        })
        .then(() => {
           axios.get('/get').then((response) => {
             this.setState({ result: response });
           }).catch((error) => {
             this.setState({ message: error.message}) 
           })
        }).catch(error => {
          this.setState({ errorMessage: error.message })
        }),
      
     }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM