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...
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);