0

I'm using axios.all() to resolve an indeterminate number of different requests. Let's say for this example, the number of calls is 3.

For all of those requests, I need to modify a value in axios' params to retrieve a different page from the api per request:

params: { page: 1 } // request 1
params: { page: 2 } // request 2
params: { page: 3 } // request 3

The issue is that axios is requesting page: 3 3 times, as if it's holding onto the last requestConfig provided for the promises.

Here's my code:

function request(requestConfig) {
  // ... axios config such as baseURL, api authentication, etc.

  // [TEST A] - correct page # param
  console.log(requestConfig)

  return axios(requestConfig)
    .then ( res => {
      // [TEST B] - incorrect page # param, always last page
      console.log(requestConfig)
      return res.data
    })
    .catch( error => {
      // error
    })
}


export default {
  // ... other axios request functions
  getProjects () {
    return new Promise( (resolve, reject) => {
      let projects = []
      let promises = []

      // loop through all project pages (3 for this example)
      for (let i = 1; i <= 3; i++) {
        promises.push(request({ url: 'projects', params: {
          page: i // set the page number for this request
        }))
      }

      axios.all(promises)
        .then( results => {
          // loop through the results and push them to projects[]
          results.forEach( page => {
            projects.push.apply(projects, page)
          })

          resolve(projects)
        })
        .catch( error => {
          reject(error)
        })
    }
  }
}

The odd part is the at [TEST A], the correct param page number is outputted. For [TEST B], it outputs the last page number for all requests.

I found these, but either they're not the same issue or I'm not following...

Why I getting the last promise?

Is it possible to use axios.all with a then() for each promise?

Any ideas?

scferg5
  • 2,003
  • 5
  • 22
  • 28

1 Answers1

0

I got it to work by changing the first function to:

function request(requestConfig) {
  // ... axios config such as baseURL, api authentication, etc.

  // [TEST A] - correct page # param
  console.log(requestConfig)

  // ADDED THIS TO CREATE A NEW AXIOS INSTANCE EVERY TIME
  let axiosInstance = axios.create(requestConfig)

  return axiosInstance(requestConfig)
    .then ( res => {
      // [TEST B] - incorrect page # param, always last page
      console.log(requestConfig)
      return res.data
    })
    .catch( error => {
      // error
    })
}

Not sure if that's the most performant way to accomplish this, but it achieves the end goal...

scferg5
  • 2,003
  • 5
  • 22
  • 28