Use Async/Await with Axios in React.js

后端 未结 2 655
臣服心动
臣服心动 2020-12-07 16:52

Following

How to use async/await with axios in react

I am trying to make a simple get request to my server using Async/Await in a React.js

2条回答
  •  一生所求
    2020-12-07 17:19

    In my experience over the past few months, I've realized that the best way to achieve this is:

    class App extends React.Component{
      constructor(){
       super();
       this.state = {
        serverResponse: ''
       }
      }
      componentDidMount(){
         this.getData();
      }
      async getData(){
       const res = await axios.get('url-to-get-the-data');
       const { data } = await res;
       this.setState({serverResponse: data})
     }
     render(){
      return(
         
    {this.state.serverResponse}
    ); } }

    If you are trying to make post request on events such as click, then call getData() function on the event and replace the content of it like so:

    async getData(username, password){
     const res = await axios.post('url-to-post-the-data', {
       username,
       password
     });
     ...
    }
    

    Furthermore, if you are making any request when the component is about to load then simply replace async getData() with async componentDidMount() and change the render function like so:

    render(){
     return (
      
    {this.state.serverResponse}
    ) }

提交回复
热议问题