0

I am using React and I need advice on the best way to filter dates in a JSON object that is populated from a fetch call to an API.

I have a Date range picker component that sets the state with the chosen dates. at page load the the data is populated into an HTML table, when the user selects the chosen dates from the date range picker and clicks the filter button I need the html table to be updated with results that fall between the chosen date ranges.

my constructor has the starting state:

this.state = {
  bookings: {},
  selectionRange : {
    startDate: new Date(),
    endDate: new Date(),
    key: "selection"
  }
}

My Date Button to filter the dates, my attempt to convert the date from a string to a valid date.

onbuttonsubmit()  {
  var options = { year: 'numeric', month: 'long', day: 'numeric' };
  console.log("Testing:", new Date(this.state.bookings.FromDate).toLocaleDateString([],options));
}
     
<button onButtonSubmit={this.onbuttonsubmit}>Filter Dates</button>

I have attached an image showing the bookings{} json:

enter image description here

1
  • so you need FromDate to be between the date range? Commented Aug 3, 2020 at 15:08

1 Answer 1

1

Since FromDate at your bookings object is a string and filters are of type Date, you could do the following, provided that you want to do a search based on FromDate:

 onbuttonsubmit = () =>  {
    this.setState( { bookings : this.state.bookings.filter( book => new Date(book.FromDate).getTime() >= this.state.startDate.getTime() && new Date(book.FromDate).getTime() <= this.state.endDate.getTime())});
}
Sign up to request clarification or add additional context in comments.

8 Comments

thank you, I have done what you suggested but I am getting typeError: cannot read property setState of undefined
ok so you havent binded the method. see my updated answer then.
Apostolos, since my book.fromDate is a json string "2019-06-14T00:00:00" the .getTime() is not valid, could I create a function within a function to resolve this? × TypeError: Cannot read property 'getTime' of undefined
it is new Date(book.FromDate).getTime(). this is valid
try at your console this new Date('2019-04-26T00:00:00').getTime() to see that it is working
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.