Search code examples
reactjsaxioses6-promise

React JS & Axios chaining promies


I am developing a react js application and we are using a promise based library axios for calling APIs.

Now, in the initial part of application, user gets a login page, when the login is successful, we contact different systems to retrieve some extra information about user.

axios
    .get('url to authentication endpoint') // 1st call
    .then(response => {
        // if login is successful
        // 1. retrieve the user preferences like, on the customised screens what fields user wanted to see
        axios.get('user preference endpoint') // 2nd call
        // 2. send a request to one more external systems, which calculates what user can see and not based on LDAP role
        axios.get('role calculation endpoint') // 3rd call
    })
    .catch(error => {
    })

Now I can see that I can use

axios.all()

for second and third call, but with promised based client, how to chain first and second call? To retrieve user preferences, I have to wait for user to be authenticated.

How to chain this calls in a promise based way, rather than callback style?


Solution

  • as mentioned in the thread for this Github issue, axios() and axios.all() return Promise objects which can be chained however you see fit:

    axios.get('/auth')
      .then(function(response) {
        return axios.all([ axios.get('/preferences'), axios.get('/roles') ]);
      })
      .then(function(responses) {
        const [
          preferencesResponse,
          rolesResponse
        ] = responses;
        // do more things
      })
      .catch(function(error) {
        console.log(error);
      });