[Vuejs]-Two similar requests, how to improve?

1👍

You can extract a (global?) function that fetches data from your api:

const fetchData = (uri = "") => fetch(`${BASE_URL}${uri}`)
  .then(response => response.json());

For the update, you can have a local function:

const updateData = data => {
  allNews.value = data.items;
  totalPages.value = data.nav.total
};

You might also want to extract your error handling logic if it’s shared:

const handleError = err => console.error(err);

And with these two you can rewrite your functions:

const getAllNews = () =>
  fetchData("/")
    .then(updateData)
    .catch(handleError);

const fetchMore = () => {
  currentPage.value += 1
  return fetchData(`/${currentPage.value}/`)
    .then(updateData)
    .catch(handleError);
}
👤Vivick

Leave a comment