Creating a script to divide two date ranges using nested functions and sending a request to the API via JavaScript

I have implemented a component that displays news based on a specified date range. Currently, the API I am using only provides data for the past 90 days. However, I aim to enhance this component by allowing users to select a date range of 1 year. To achieve this, I plan to divide the 1-year period into chunks of 90 days and fetch data accordingly. Additionally, I need the request to halt after retrieving the first set of data within the 90-day interval.

For instance:

startDate = 2021-12-27

endDate = 2022-12-27

Identify the date that is 90 days before the chosen endDate (startDate = 2022-10-27). If there is data available, the loop should break. Otherwise, the system should send a request for the previous 90-day period.

This is my code:

function requestToDataNews(startDate, endDate) {
    return new Promise((resolve, reject) => {
      http.get(`/test=&start_date=${startDate}&end_date=${endDate}`, { timeout: 40000 }
      )
        .then((response) => {
          if(response.data.response_code === 200){
            resolve(response.data);
          } else {
            reject(response.data);
          }
        })
        .catch((error) => {
          reject(error);
        }).finally(() => {
          commit('loadingBar', false);
        });
    });
 }
 commit('loadingBar', true);
 let startDate = '2022-12-27';
 let endDate = '2021-12-27';
 
 const differentDays = tools.getDifferentDaysRange(endDate, startDate, 'days');
 const currentNewsData = [];
 
 if (differentDays > 90 && differentDays <= 365) {
   for (let i = 0; i < Math.ceil(differentDays / 90); i += 1){
     startDate = moment(endDate).subtract('months', 2).format('YYYY-MM-DD');
     const newsData = requestToDataNews(startDate, endDate);
     if (newsData.is_success) {
       currentNewsData.push(...newsData.data);
     }
   }
 }
}

PLEASE NOTE: There seems to be an issue with my code's functionality.

Answer №1

Avoid using string dates for comparisons; opt for timestamps and verify the dates instead.

function fetchNewsData(startDate, endDate) {
  return new Promise((resolve, reject) => {
    http.get(`/test=&start_date=${startDate}&end_date=${endDate}`, { timeout: 40000 })
      .then((response) => {
        if (response.data.response_code === 200) {
          resolve(response.data);
        } else {
          reject(response.data);
        }
      })
      .catch((error) => {
        reject(error);
      }).finally(() => {
        commit('loadingBar', false);
      });
  });
}

const onStartDate = '2021-12-27';
const onEndDate = '2022-12-27';

// conversion to timestamp
const startDateStamp = new Date(onStartDate).getTime();
const endDateStamp = new Date(onEndDate).getTime();

// calculating difference in days
const diffDaysStamp = Math.ceil((endDateStamp - startDateStamp) / (1000 * 60 * 60 * 24));

if (diffDaysStamp <= 90) {
  fetchNewsData(onStartDate, onEndDate);
} else {
  const diffDate = Math.ceil(diffDays / 90);
  const dateArr = [];
  for (let i = 0; i < diffDate; i++) {
    const startDate = new Date(onStartDate).getTime();
    const endDate = new Date(onEndDate).getTime();
    const diffDays = Math.ceil((endDate - startDate) / (1000 * 60 * 60 * 24));
    if (diffDays <= 90) {
      dateArr.push({
        startDate: new Date(startDate).toISOString().slice(0, 10),
        endDate: new Date(endDate).toISOString().slice(0, 10),
      });
    } else {
      const newEndDate = new Date(startDate + 90 * 24 * 60 * 60 * 1000);
      dateArr.push({
        startDate: new Date(startDate).toISOString().slice(0, 10),
        endDate: new Date(newEndDate).toISOString().slice(0, 10),
      });
    }
  }
  dateArr.forEach((item) => {
    fetchNewsData(item.startDate, item.endDate);
  });
}

This is just an example, so the code may not be operational. I have not verified it. It's meant to provide you with an idea.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Adding a new property to a JSON object in a specific position

This might be a Repeat: Does JavaScript Guarantee Object Property Order? I am curious about inserting a property into a JSON object at a specific location. Consider this Javascript object: var data = { 0: 'lorem', 1: 'dolor sit&apo ...

Choosing multiple items using ng-checked and ng-model in AngularJS

I am working with an Ionic application and encountering a minor issue, much like AngularJS. <ion-list class="list-inset subcategory" ng-repeat="item in shops"> <ion-checkbox class="item item-divider item-checkbox-right" ng-model="selectAll" ...

What is the method to retrieve the current index of an item in v-carousel?

My current code successfully cycles a carousel, but I would like to display the item title underneath the image instead of on top. I believe creating a new data value that updates with each change in the carousel is the solution. However, I am struggling ...

Unable to utilize object functions post-casting操作。

I've encountered an issue while trying to access some methods of my model object as it keeps returning an error stating that the function does not exist. Below is the model class I have created : class Expense { private name: string; private ti ...

responding with a value of undefined for the get request

My current project involves URL shortening, but I keep encountering an 'undefined' result in my GET request. Additionally, sometimes I also receive a blank page as a result. Despite everything appearing to be correct based on my knowledge, I&apos ...

How can one change the color of movable tiles to red while keeping the rest of the tiles in their original state in a puzzle game?

In this section of our code, the function moveTile is responsible for moving a tile. How can I modify it so that the hover color changes to red? function moveTile(identity) { var emptyId = findEmptySpace(); if (isEmptyNeighbor(identity)) { document.ge ...

Unable to submit form in Nextjs using react-bootstrap

Instructions To create a registration form, follow these steps: Fill out the form on the register page and then click submit. The react-bootstrap button will trigger the handleSubmit() function using onSubmit={}. Expected vs Actual Outcome I attempted va ...

Run JavaScript code after the completion of loading a generic handler in ASP.NET

I am facing a challenge with a gridview that contains a list of pdf files. Whenever a user clicks on a pdf, it should display the file inline on the page. I have been trying to execute some javascript after the pdf has finished loading, but I'm encoun ...

Properly defining the selector for the element.closest() method in the DOM

How can I access the ID of the outermost div from the inner button element in this HTML snippet? <div id="menu_level_0" class="menu_level"> <div class="editor"> <div class="ui_detail ...

Remove the ahover effect on touch for iPad and iPhone devices

I have a button with a:hover effect, but I want to disable hover on iPad and iPhone. It's not working. $(document).ready(function () { $(".content").hide(); $(".open1").click(function () { $(this).next().slideT ...

Add a selection of paths from a different package into the Router

Seeking a quick solution here. I have the following code snippet and I am looking to efficiently import a multitude of routes from my package. These routes should be managed by the package I am constructing. If I introduce a new page in the package (e.g., ...

Alternative solution to avoid conflicts with variable names in JavaScript, besides using an iframe

I am currently using the Classy library for object-oriented programming in JavaScript. In my code, I have implemented a class that handles canvas operations on a specific DIV element. However, due to some difficulties in certain parts of the code, I had t ...

Angular 4 with Universal: Implementing 404 Status Code in Header for /404 Page Component

After researching and reviewing numerous StackOverflow inquiries, I have come to the conclusion that headers are derived from responses served by servers, making it a non-issue. I attempted to rectify the situation from my server.ts file but unfortunately ...

Substituting the Line Break Character

I could use some assistance with replacing a special character in a string using a regular expression that's proving tricky for me to solve. The string I'm working with contains a special character "↵" that I want to replace with a comma. var ...

I'm unsure of the most efficient way to condense this statement

$(document).ready(function(){ if ($(window).width() <961){ $('.item').on('click',function(){ /*---do something---*/ }) }else{ $('.item').on('click',function(){ ...

Setting up instagram-node-lib for managing subscriptions

I am currently working on implementing real-time updates for a specific hashtag and displaying the image on the screen. However, I am facing issues setting up my node.js server using the instagram-node-lib module. Even after running the file (node server.j ...

Error: JSON data abruptly terminated (Node.js)

As a beginner developer diving into the world of API's, I've encountered a recurring error in Node.js that seems to be causing crashes: SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) at IncomingMessage.<anonymo ...

Ways to simulate a class instance that is being received from a file with a different class instance

I am struggling with a specific file in my project // src/history import { createBrowserHistory } from 'history' const history = createBrowserHistory(); export default history; The variable history represents an instance of the BrowserHistory cl ...

the drawbacks of using mixins as outlined in Vue's official documentation

The documentation mentions a downside to mixins in Vue 2. One limitation is reusability: as parameters cannot be passed to the mixin in order to change its logic, their flexibility in abstracting logic is reduced. I'm struggling to fully grasp this ...

What is the best way to transfer form data to another function without causing a page refresh?

Currently, I am in the process of developing a series of web applications using REACT JS. One specific app I am working on involves a modal that appears upon a state change and contains a form where users can input their name along with some related data. ...