close

[Solved] Use Async/Await with Axios in React.js

Hello Guys, How are you all? Hope You all Are Fine. Today I get the following error Use Async/Await with Axios in React.js in javascript. So Here I am Explain to you all the possible solutions here.

Without wasting your time, Let’s start This Article to Solve This Error.

How Use Async/Await with Axios in React.js Error Occurs?

Today I get the following error Use Async/Await with Axios in React.js in javascript.

How To Solve Use Async/Await with Axios in React.js Error ?

  1. How To Solve Use Async/Await with Axios in React.js Error ?

    To Solve Use Async/Await with Axios in React.js Error Async/Await with axios useEffect(() => { const getData = async () => { await axios.get('your_url') .then(res => { console.log(res) }) .catch(err => { console.log(err) }); } getData() }, [])

  2. Use Async/Await with Axios in React.js

    To Solve Use Async/Await with Axios in React.js Error Async/Await with axios useEffect(() => { const getData = async () => { await axios.get('your_url') .then(res => { console.log(res) }) .catch(err => { console.log(err) }); } getData() }, [])

Solution 1

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(
     <div>
       {this.state.serverResponse}
     </div>
  );
 }
}

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 (
  <div>{this.state.serverResponse}</div>
 )
}

Solution 2

Async/Await with axios 

  useEffect(() => {     
    const getData = async () => {  
      await axios.get('your_url')  
      .then(res => {  
        console.log(res)  
      })  
      .catch(err => {  
        console.log(err)  
      });  
    }  
    getData()  
  }, [])

Summery

It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you? Thank You.

Also Read

Leave a Comment