Hugo
Hugo

Reputation: 170

Axios - multiple requests for the same resource

I'm creating an app where in one page, I have two components requesting the same http resource. In this case I'm using axios and here's one example:

axios.get('/api/shift/type')
        .then(
            (response) => {
                self.shiftTypes = response.data;
                success(response.data)
            },
            (response) => {
                error(response)
            }
        );

The issue lies in them requesting it almost at the same time. If Component A makes the request at the same time as Component B, 2 request calls are made and they'll get the same data. Is there a way to check if axios currently has an unresolved promise and return the result to both components once the request is resolved?

Not sure if it helps but the app is being built using the vue framework

Thanks

EDIT: I tried storing the promise in memory but Component B never gets the response

getShiftTypes(success, error = this.handleError, force = false) {
    if (this.shiftTypes && !force) {
        return Promise.resolve(this.shiftTypes);
    }

    if (this.getShiftTypesPromise instanceof Promise && !force) { return this.getShiftTypesPromise; }

    let self = this;
    this.getShiftTypesPromise = axios.get('/api/shift/type')
        .then(
            (response) => {
                self.shiftTypes = response.data;
                self.getShiftTypesPromise = null;
                success(response.data)
            },
            (response) => {
                error(response)
            }
        );
    return this.getShiftTypesPromise;
}

Upvotes: 5

Views: 3688

Answers (1)

Jonathan Sterling
Jonathan Sterling

Reputation: 604

Consider using a cache:

let types = { lastFetchedMs: 0, data: [] }

async function getTypes() {

  const now = Date.now();

  // If the cache is more than 10 seconds old
  if(types.lastFetchedMs <= now - 10000) {
    types.lastFetchedMs = now;
    types.data = await axios.get('/api/shift/type');
  }

  return types.data;
}

while(types.data.length === 0) {
  await getTypes();
}

Upvotes: 3

Related Questions