简体   繁体   中英

How can I rewrite my method to async/await?

In my react app I'm making a post request to the server with the help of axios:

 onSubmit = (results) => {
     axios.post("http://localhost:8080/simulate/", results)
      .then( (response) => this.setState({results: response.data.results}))
      .catch( (error) => this.setState({results: error.response.data, hasError: true})
      ); 
  }

How can I rewrite this method to async/await ?

onSubmit = async (results) => {
  try {
    const response = await axios.post("http://localhost:8080/simulate/", results)
    this.setState({results: response.data.results})
  } catch (error) {
    this.setState({results: error.response.data, hasError: true})
  }
}

Edit - without Axios

If you don't want to use Axios, you may use the fetch api :

onSubmit = async (results) => {
  try {
    const response = await fetch("http://localhost:8080/simulate/", {
      method: 'POST',
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(results)
    })
    const { data } = await response.json()
    this.setState({results: data.results})
  } catch (error) {
    this.setState({results: error.response.data, hasError: true})
  }
}

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