change date using useState reactjs

Viewed 652

app.js file

import React, { useState } from 'react';
import Header from '../header/header';
import Day from '../day/day'
import {BrowserRouter as Router} from 'react-router-dom';
import './app.css';

export default function App() {
        const [currentDay, setDay] = useState(new Date());
        console.log(currentDay)
        function nextDay() {
            console.log("next clicked");
            let nextDate = new Date(currentDay.getTime());
            nextDate = nextDate.setDate(nextDate.getDate() + 1);
            setDay(nextDate);

        }
        return (
            <>
            <Router>
                <Header/>
            </Router>
            <Day 
            date={currentDay}
            nextDay={nextDay}/>
            </>
        )
}

day.js file contains Day - component

import React from 'react';
import Moment from 'react-moment';
import './day.css';

export default function Day({date, nextDay}) {
    return (
        <div className="day-container">
            <Moment>{date}</Moment>
            <span onClick={() => nextDay()}>next</span>
        </div>
    )
}

console screen

After clicking on next, Date object becomes timestamp and after second click throws the error(currentDay.getTime is not a function) I dont understand the reason of that.

1 Answers

Date.prototype.setDate updates the date and returns epoch value of the date.

You do not need the returned value and can simply do:

let nextDate = new Date(currentDay.getTime());
nextDate.setDate(nextDate.getDate() + 1);
setDay(nextDate);

Your original variable can still be used.

Related