Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Fetching Data with Axios

fetching data with axios, return data and make a new request in case of 500 error (react)

hi there

I want to take this app to next level having the following code:

 return axios.get(`https://fly-api.herokuapp.com/api/v1/aircraft/`+query )
           .then(result => {
              this.setState({ planes: result.data });
              })      

(i have to use this syntax for Heroku) What I try to do I to make a new request to the server in case the API return a 500 (Internal Server Error) status

Please Help

for example here I am stuck

 performSearch= (query) => {


           return axios.get(`https://fly-api.herokuapp.com/api/v1/aircraft/`+query )
           .then(result => {
              this.setState({ planes: result.data });
              })      
              // how can I write the code in order to perfom the following actions  here 
           /// if status === 500 
          // then make a new  axios.get(`https://fly-api.herokuapp.com/api/v1/aircraft/`+query )???
             //return result 
          .catch(error => {
            console.log('Error fetching and parsing data', error);
          }); 

         } 

1 Answer

const performSearch = (query) => {
  axios.get(`https://fly-api.herokuapp.com/api/v1/aircraft/${query}`).then(result => {
    if (result.status === 500) {
      performSearch();
    }
    this.setState({
      planes: result.data
    });
  }).catch(error => console.log('Error fetching and parsing data', error));
}
Tom Geraghty
Tom Geraghty
24,174 Points

Miguel's answer should do the trick however there is another option with axios as they have a thing called "interceptors".

The documentation has more info on how to add interceptors to take action on the data either before it is sent or after it returns but before .then() here https://github.com/mzabriskie/axios.