Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

185
Views
set and get date and time in localStorage in react datepicker
import React, { Component } from "react";
import { connect } from "react-redux";
import "react-datepicker/dist/react-datepicker.css";
import DatePicker from "react-datepicker";

class Date extends Component {
  constructor(props) {
    super(props);
    this.handleChange = this.handleChange.bind(this);
    this.state = {
      startDate: "",
    };
  }

  async componentDidMount() {

    let startDate = JSON.parse(localStorage.getItem("Date") || "");
 {});

    this.setState({
        startDate
    });
  }
  handleChange(date) {
    localStorage.setItem("Date", JSON.stringify(date));
    this.setState({
      startDate: date,
    });
  }

  render() {
    return (
      <div>
        <div className="form-group">
          <DatePicker
            className="date"
            selected={this.state.startDate}
            onChange={this.handleChange}
            showTimeSelect
            timeFormat="HH:mm"
            timeIntervals={20}
            timeCaption="time"
            dateFormat="MMMM d, yyyy / h:mm"
            placeholderText="Select Date and Time"
          />
        </div>
      </div>
    );
  }
}

const mapStateToProps = (state) => ({});

export default connect(
  mapStateToProps,
  {}
)(Date);

When I select date and time from datepicker then pass date and time value of handleChange function as a parameter date. date parameter have the value of date and time and I am trying to set this value in localStorage but when I get data from local storage, it shows below error...

enter image description here

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

There were multiple errors in your code. Parsing an empty string, storing empty string in startingDate causing DatePicker to get Invalid Date. Also change your class name to something other than Date as its predefined Class name in JavaScript. Try below code

class DateComponent extends Component
...
componentDidMount() {
    let startDate = localStorage.getItem("Date") ? new Date(JSON.parse(localStorage.getItem("Date"))) : "";
    this.setState({
      startDate: startDate
    });
  }
...
export default connect(
  mapStateToProps,
  {}
)(DateComponent);
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!