ReactJS and JavaScript offer a convenient solution for extracting the most recent date from an array of date fields during the selection process

I have a table in ReactJS that displays an array of items. Each item has the following fields:

id, requested_date, and location

Additionally, there is another field called "date" which is located outside of the array. This "date" should always display the latest date from the array's requested_date.

The structure is as follows:

Item array

id     requested_date      location
101     2018-03-21          NY
102     2018-03-22          NY
103     2018-03-20          NY

Date : 2018-03-22

In the example above, the Date should be set to "2018-03-22" because it is the latest requested_date in the items array.

Please see my code below for reference.

class Details extends React.Component {
    constructor(props) {
    super(props);
    this.requestedDateChangeonSelectionEvent=this.requestedDateChangeonSelectionEvent.bind(this);
    this.state = { item: props.item };

}
requestedDateChangeonSelectionEvent(dateSelected)
{

    var item = this.state.item;
    var lines = item.order_items;
    if(lines.length == 1)
        {
            var latest = dateSelected; 
            console.log("Length 1");

        }

    else {
        var latest = dateSelected; 
     for(var i=0;i<lines.length;i++) {
         if(moment(lines[i].requested_date) >= moment(latest)) {
             latest=lines[i].requested_ship_date;
             }
         }

    }
       this.state.item.date=latest;
        this.setState({ item: item });

}

render() {
   return (<tbody>{ this.props.items.map((item) => <DetailsItem key={ item.line_id } item={ item } 
                                                        requestedDateChangeonSelectionEvent={ this.props.requestedDateChangeonSelectionEvent }
                                                     />) }

              </tbody>);    
      }
}

class DetailsItem extends React.Component {
constructor(props) {
    super(props);
    this.handleRequestedShipDate = this.handleRequestedShipDate.bind(this);
}

handleRequestedShipDate(e)
{

    var item=this.state.item;
    this.setState({item:item});
    var charCode = (e.which) ? e.which : e.keyCode;
    var dateSelected=e.target.value;
    e.preventDefault();
    this.props.requestedDateChangeonSelectionEvent(dateSelected);

}
render() {


    return (
            <tr>
            <td><input name="line_number" type="text" value={ this.state.item.line_number } onChange={ his.handleInputChange }/> </td>
            <td><input name="requested_date"  type="date" value={ this.state.item.requested_date } onChange={ (e) => { this.handleRequestedShipDate(e); this.handleInputChange(e); } }  </td>
            <td><input name="source_location" type="text" value={ this.state.item.source_location } onChange={ this.handleInputChange }/> </td>
            </tr>   
             );
    }
}

I am trying to implement a logic where the latest date is automatically updated when selecting a requested_date. It works fine for the first item, but for subsequent items, it does not update with the current selection. Instead, it uses the previous selection.

The problem can be described as follows:

The issue is not with the date comparison itself; that part works as expected. The problem lies in maintaining the correct values and updating them during the selection process. For example:

id     requested_date      location
101     2018-03-21          NY
102     2018-03-22          NY
103     2018-03-20          NY

If I make a change in the requested_date for the 102nd record, like this:

id     requested_date      location
101     2018-03-21          NY
102     2018-03-19          NY
103     2018-03-20          NY

I would expect that the change to 2018-03-19 should happen immediately during the selection, and then compare it with the other requested_dates to set the latest date as 2018-03-21.

However, what actually happens is that it retains the old value of 2018-03-22, therefore the array element's requested_date does not change during the selection process.

Answer №1

I believe that this question has already been addressed in another post: Comparing dates and times with Moment.js.

A possible solution to your issue is utilizing the diff function provided by momentjs.

In JavaScript, when attempting to compare two moment objects, only their references are compared rather than their actual values (due to the inability of JavaScript to compare dates using >=). Therefore, employing the diff function will yield the precise difference between the dates (which will be represented as integers, a type that JavaScript can handle for comparison purposes!)

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

Managing empty functions as properties of an object in a React, Redux, and Typescript environment

I'm feeling a little uncertain about how to properly test my file when using an object with a function that returns void. Below are the details. type Pros={ studentid: StudentId pageId?: PageID closeForm: () => void } When it comes to creating ...

Ways to customize the border color on a Card component using React Material UI

Is there a way to change the border color of a Card component in React Material UI? I attempted using the style property with borderColor: "red" but it did not work. Any suggestions on how to achieve this? ...

Implementing a change event upon setting a value to an input element using JavaScript

My plan is to develop a Chrome extension that can automatically fill passwords. The code for this functionality looks like the following: //get the account document.querySelector("input[type=text]").addEventListener('input', () => { ...

Can you explain the slow parameter feature in Mocha?

While configuring mochaOpts in Protractor, one of the parameters we define is 'slow'. I'm unsure of the purpose of this parameter. I attempted adjusting its value but did not observe any impact on the test execution time. mochaOpts: { re ...

Issues with jQuery slide operation

I'm facing an issue with jQuery and I can't figure out where it's coming from. Here is the error message that keeps showing up in the console: Uncaught TypeError: Object [object Object] has no method 'getElement' script_16.js:46Un ...

What is the significance of using flexGrow in the parent div of a Material UI grid?

I am currently working on understanding a code example located at https://codesandbox.io/s/9rvlm which originates from the Material UI documentation (https://material-ui.com/components/grid/): import React from 'react'; import PropTypes from &ap ...

Convert a form into plain text utilizing CSS with minimal usage of jQuery or Javascript

I am working on an HTML page which has a form with various tags such as checkboxes, dropdowns, and more. When a button is clicked, I want to display the same form as plain text in a popup using jQuery dialog. Currently, I have managed to show the form in ...

What is the process to create a sticky Material UI grid element?

Currently, I am in the process of developing the front-end for a shopping cart. To organize the content, I have split the container into two columns using Grid container and Grid item. In each column, various components are placed - the left side containin ...

Tips for exchanging JSON data between HTML and PHP using jQuery Ajax?

Hello there! I am just starting to learn PHP and jQuery, and I have been experimenting with some code to understand how things work. However, I seem to be having issues with sending data back and forth between my webpage and the PHP file on the server. Her ...

Initiate a click action upon receiving a focus event

I can't seem to figure out why this code is not functioning as expected: $('a').focus( function() { $(this).click(); }); Context: I am working on developing a form where navigating through different elements (such as textboxes) will au ...

`How can you generate navigation paths using the ngRoute module?`

I am currently working on creating a basic navigation system like the one illustrated below: html: <html ng-app="myapp"> <body> <ul> <li><a href="pages/sub1">sub1</a></li> <li><a href="pages/ ...

Developing a transparent "cutout" within a colored container using CSS in React Native (Layout design for a QR code scanner)

I'm currently utilizing react-native-camera for QR scanning, which is functioning properly. However, I want to implement a white screen with opacity above the camera, with a blank square in the middle to indicate where the user should scan the QR code ...

Using a series of identical divs to dynamically update the image URL

Greetings! I am a newcomer to the world of web development and I have decided to hone my skills by creating a small website for my mother! My goal is to replicate a specific div multiple times while changing only the image URL and the heading caption. < ...

Using React to access a function from a different component in your application

I am working on implementing a topbar menu that requires access to a specific react component. The challenge I am facing is that within the topbar file, I do not directly render the components I need to interact with but still want to be able to call a fun ...

What steps should I take to ensure that clicking this button triggers the API request and returns the data in JSON format?

I'm attempting to have the button with id 'testp' return an api request in json format, however it seems to not be functioning properly. You can find the HTML code link here: https://github.com/atullu1234/REST-API-Developer-1/blob/main/js-bu ...

Is there any method to determine whether a floated element has been pushed down?

Imagine a dynamic menu with floating elements, each set at a width of 150px. As the menu's width decreases, the elements progressively move to the next row. You are contemplating how to detect when an element has been moved down. One approach could b ...

Error: `vendor` is not defined when attempting to use DllPlugin and DllReferencePlugin together

I encountered a strange issue while attempting to enhance the build time of my webpack bundle. I followed a insightful tutorial on optimizing webpack, which suggested extracting all vendor libraries and building them using separate webpack configuration fi ...

Tips for correctly loading all elements on an HTML page before making CSS modifications

This question has been asked several times in the past. I am asking because when I used the on ready callback in jQuery, it did not change the placeholder text of my element "search_input". $( document ).ready(function() { $("#search_input").attr(' ...

The oddity of a lone quotation mark trying to break

var x = "Test \'" > undefined var y = "Test '" > undefined x === y > true x > "Test '" https://i.stack.imgur.com/ZrHo5.jpg Aha! Both of these strings are actually equal (as shown in the example code) - but why is that the ...

Retrieving the input[text] value in TypeScript before trimming any special characters

One of the tasks I am working on involves a form where users can input text that may contain special characters such as \n, \t, and so on. My objective is to replace these special characters and then update the value of the input field accordingl ...