Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Two similar requests, how to improve?

I have two requests to the server. The first one at the initial rendering of the page, the second one – by the "Show more" button.

request 1:

const getAllNews = () => {
 fetch(`${BASE_URL}`)
  .then(response => response.json())
  .then(data => {
    allNews.value = data.items
    totalPages.value = data.nav.total
  })
 .catch(err => console.error(err));
}

request 2:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const fetchMore = () => {
 currentPage.value += 1
 fetch(`${BASE_URL}/${currentPage.value}/`)
  .then(response => response.json())
  .then(data => {
   allNews.value = data.items
   totalPages.value = data.nav.total
   })
  .catch(err => console.error(err));
}

There is code duplication here, what should be used in order to optimize this code?

>Solution :

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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading