0

I am trying to have previous day, current day, and next day buttons so for example, if I press the next button, it will take today's date, add one to today's date and show tomorrows information on the page.

My click handler looks like:

const nextHandler = () => {
    let resDate = new Date();
    let year = resDate.getFullYear();
    let day = new Date().getDate();
    let month = resDate.getMonth() + 1;

    if (month.toString().length < 2 || day.toString().length < 2) {
      month = ('0' + month).slice(-2);
      day = ('0' + day).slice(-2);
    }

    day = parseInt(day) + 1;
    let newDate = `${year}-${month}-${day}`;
    
    // newDate --> 2021-04-11
     history.push(`/dashboard?date=${newDate}`);
  };

When I click my next button I get taken to: http://localhost:5000/reservations?date=2021-04-12 exactly as I would like. However, I am only able to add to the day once. How am I continuously able to update this query string?

  • Adding 1 to the day isn't a good way to add 1 day to a Date since it won't handle end of months. See [*How can I add 1 day to current date?*](https://stackoverflow.com/questions/9989382/how-can-i-add-1-day-to-current-date) – RobG Apr 12 '21 at 05:14

2 Answers2

1

You're only ever starting with new Date(); on your second line so it'll only ever increment once. You'll have to read from the querystring a value to put in new Date(VALUE); if it's set so that it continues to remember. Here's a stackoverflow answer from something like that: How can I get query string values in JavaScript?

You're code may look like:

const urlParams = new URLSearchParams(window.location.search);
const dateParam = urlParams.get('date');
let resDate = dateParam ? new Date(dateParam) : new Date();
Mathew Berg
  • 28,625
  • 11
  • 69
  • 90
0

It's nextHandler is using today's date to increment rather than the date of the query string.

On the first click, nextHandler today's date to increment. But, the next click should start from the date in the query string.

I hope that solve your problem.