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) => { }
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...
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With