0

Background: I have an infinite scroll component that continually makes requests to a third party API as the user gets to the bottom div. I'm running into a problem where if the user switches pages before the outstanding requests finish it creates a memory leak.

What I tried: I tried using a global cancel token as suggested in this answer to cancel all outstanding api requests, but this prevents all future requests.

Question: I'm looking for a way to cancel ALL current & previous requests across all my API calls, from outside the api file, while still allowing future requests.

My api file looks like this:

import React from 'react'
import axios from 'axios'

export const fetchAvatars = (query, amount) => {
  return axios.get('https://pixabay.com/api/', {
    params: {
      key: process.env.PIXABAY_API,
      q: query,
      orientation: 'vertical',
      per_page: amount,
      image_type: 'photo'
    }
  })
}

export const fetchVideos = (amount, category, editorsChoice, query) => {
  return axios.get('https://pixabay.com/api/videos/', {
    params: {
      key: process.env.PIXABAY_API,
      q: query,
      per_page: amount,
      category: category,
      editors_choice: editorsChoice,
      min_height: 1080,
      orientation: 'horizontal'
    }
  })
}

export const fetchVideoFromID = (id) => {
  return axios.get('https://pixabay.com/api/videos/', {
    params: {
      key: process.env.PIXABAY_API,
      id: id
    }
  }).catch(err => {
    if (!err.response) {
      console.log('network error, probably bad id')
    }
    else console.log(err)
  })
}

export const fetchPictureFromID = (id) => {
  return axios.get('https://pixabay.com/api/', {
    params: {
      key: process.env.PIXABAY_API,
      id: id
    }
  }).catch(err => {
    console.log(err)
  })
}

export const getRandomName = () => {
  return axios.get('https://randomuser.me/api/?nat=gb,au,ca')
}
Robert C
  • 756
  • 10
  • 25
  • Does this answer your question? [how to cancel/abort ajax request in axios](https://stackoverflow.com/questions/38329209/how-to-cancel-abort-ajax-request-in-axios) – Álvaro Tihanyi Jan 30 '20 at 01:39
  • @ÁlvaroTihanyi No it does not. I have already read that thread & the axios docs on cancel tokens. – Robert C Jan 30 '20 at 01:42
  • Can you update how you have tried cancel token ? – Nipun Jain Jan 30 '20 at 06:54
  • @NipunJain I created a global cancel token source at the top of the api file then referenced that source in every api call's config parameters via `cancelToken: source.token` . I exported the source then called cancel on it when components unmounted. – Robert C Jan 30 '20 at 17:42

0 Answers0