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:
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);
}