I'm currently fetching categories from WordPress using REST. The 100 limit forced me to do multiple queries. Here is my current function for this. It's not pretty. Can anyone come up with something more concise?
export async function getAllCategories() {
let arr = []
const res = await fetch(`${API_URL}wp/v2/categories?per_page=100&page=1`)
const data = await res.json()
const totalPages = res.headers.get("X-WP-TotalPages")
data.forEach((el) => {
arr.push(el)
})
let i = 2
while (i <= totalPages) {
const res = await fetch(`${API_URL}wp/v2/categories?per_page=100&page=${i}`)
const data = await res.json()
data.forEach((el) => {
arr.push(el)
})
i++
}
return arr
}
You could define a secondary function getCategories which retrieves the categories for the specific page and the total number of pages.
This will remove the fetch call duplication.
Also, you can use the spread operator to avoid the forEach loops to populate the resulting array:
export async function getAllCategories() {
let result = []
let page = 1;
let totalPages = 0;
do {
const { data, total } = await getCategories(page);
result.push(...data)
totalPages = total
page++
} while (page <= totalPages);
return result
}
const getCategories = async (page) => {
const res = await fetch(`${API_URL}wp/v2/categories?per_page=100&page=${page}`)
return {
data: await res.json(),
total: res.headers.get("X-WP-TotalPages")
}
}