Make Axios Limit the Number of Responses

13,985

Solution 1

On your side there's nothing you can do until pagination is implemented on API side. Depending on the way it's implemented, you will probably make requests to API sending params like offset, page, limit- these are the most common params' names saying how many elements should API return. But if that's 3rd party provider and their docs are not saying anything about such possibility, you're most likely won't be able to do what you want

Solution 2

Actually, you can limit the number of responses from a certain API endpoint.

Just add params as an object as a second parameter while making the request.

For example:

componentDidMount() {
  axios.get('https://jsonplaceholder.typicode.com/todos',{
    params: {
      _limit: 10
     }
  })
    .then((res) => {
      this.setState({
        todos: res.data
      });
    })
}

Here you are limiting the response to 10 from jsonplaceholder API.

You could also call https://jsonplaceholder.typicode.com/todos/?_limit=10 and would get the same result.

Hope it helps.

Share:
13,985
Code Learner
Author by

Code Learner

Updated on June 04, 2022

Comments

  • Code Learner
    Code Learner almost 2 years

    I am attempting to make an axios GET call to an API to retrieve some JSON data. The data is stored in an array with multiple objects each containing the same keys. There are hundreds of objects in this array but I only want to return the first ten. I am aware I can truncate the data set once it is returned but I am wondering if there is a way to limit the amount of responses to my API call.

    Here is an example of the data set:

    [
      {
        "userId": 1,
        "id": 1,
        "title": "The Great Gatsby",
        "author": "F. Scott Fitzgerald"
      },
      {
        "userId": 1,
        "id": 2,
        "title": "1984",
        "author": "George Orwell"
      },
      {
        "userId": 1,
        "id": 3,
        "title": "The Count of Monte Cristo",
        "author": "Alexandre Dumas"
      },
    ]
    

    and my axios request is simple as well:

    router.get('/', (req, res) => {
        axios.get(`https://jsonwebsit.info.com/posts`)
            .then( response => {
                res.send(response.data)
            })
            .catch(err => {
                console.log('Error getting all data from API', err)
            })
    });
    
    • Tony Ngo
      Tony Ngo over 4 years
      Maybe pagination would help you ?
  • Boidurja Talukdar
    Boidurja Talukdar over 2 years
    How can we specify a range?