Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limit fetch results from javascript fetch

Tags:

javascript

Is there a function similar to q=sort& or q=created:& to limit number of results from a JavaScript fetch?

fetch('https://jsonplaceholder.typicode.com/posts')
  .then((res) => res.json())
  .then((data) => { }
like image 730
medveddimitri Avatar asked Oct 15 '25 18:10

medveddimitri


1 Answers

The best solution, of course, is if the https://jsonplaceholder.typicode.com/posts endpoint documents a limit or filter parameter you can send it.

Assuming the result is an array, or contains an array, the very-much-second-best solution is to filter the result (to apply criteria) and/or slice the result (to just apply a limit):

fetch('https://jsonplaceholder.typicode.com/posts')
    .then((res) => res.json())
    .then((data) => {
        data = data.filter(entry => entry.created > someValue) // Created after X
                   .slice(0, 1000);                            // Limit to 1000
        // ...use data...
    })
    .catch(error => {        // <=== Don't forget to handle errors
        // Handle error...
    });

Note: Your fetch call is missing a check on res.ok (it's not just you, a lot of people make that mistake so many that I wrote it up on my anemic little blog):

fetch('https://jsonplaceholder.typicode.com/posts')
    .then((res) => {                                      // ***
        if (!res.ok) {                                    // ***
            throw new Error("HTTP error " + res.status);  // ***
        }                                                 // ***
    })                                                    // ***
    .then((res) => res.json())
    .then((data) => {
        data = data.filter(entry => entry.created > someValue)
                   .slice(0, 1000);
        // ...use data...
    })
    .catch(error => {
        // Handle error...
    });
like image 171
T.J. Crowder Avatar answered Oct 21 '25 03:10

T.J. Crowder