Search code examples
reactjsasync-awaitaxiosmobx-state-tree

AXIOS Async/Await How to best write the code?


I am writing my first ajax call using Axios, Mobx/Mobx State Tree (MST) and Reactjs.

In MST they have something called flows what basically does the same thing as async/await

 getCustomers: flow(function * (){
       const response = yield getEnv(self).axiosInstance.get("/Customers/Get");

       if(response.status === 200){
           // response.data
        } else {
             // error though not sure what the call is? response.error?
        }
}),

Is it as simple as this? Is that how I should be checking if the status is and error or if the status was ok?


Solution

  • With mobx flow, future promise is handled the same as it is with async/await syntax, a successful resolve will be return as the result while a failed one will result in an error being thrown, waiting to be caught by a catch statement. You should use try / catch to catch the error. More on this topic can be found here: https://github.com/mobxjs/mobx-state-tree/blob/master/docs/concepts/async-actions.md

    With the sample code you post, it also depends on how your endpoint handle error and the status code it returns. Basically, axios treat a 200 response as success, and other (400, 500) as failure. If your API follow this convention, you don't need to check response.status to see if the response is successful, but rely on axios to do it for you, an example can see below:

    getCustomers: flow(function * (){
           try {
              const response = yield getEnv(self).axiosInstance.get("/Customers/Get");
              // Do something here if 200 response returned
           } catch (err) {
              // Error handling here when 500 returned
           }
    })