I am trying to give few dates to state.periods array. But it is not working. My code is as follows.
class SmallTable extends Component {
constructor(props) {
super(props);
console.log(props.startDate)
this.state = {
turns: [],
periods: []
}
}
componentDidMount() {
//calculate years/ months and keep in one array
const today = new Date();
var periods1 = [];
if (this.props.period=="year") { //if year calculate from last year last date
const lastYearLastDate= new Date(new Date().getFullYear()-1, 11, 31)
periods1.push(lastYearLastDate.getFullYear()+"-"+(lastYearLastDate.getMonth()+1)+"-"+lastYearLastDate.getDate());
var lastYearFirstDate= new Date(lastYearLastDate.getFullYear()-1,0,1);
//for the remaining periods
for (var i=0;i<this.props.numberOfPeriods-1;i++) {
periods1.push(lastYearFirstDate.getFullYear()+"-"+(lastYearFirstDate.getMonth()+1)+"-"+lastYearFirstDate.getDate());
lastYearFirstDate = new Date(lastYearFirstDate.getFullYear()-1,0,1);
}
}
else if (this.props.period=="month") {//if month calculate from last month last date
var d=new Date(); // current date
d.setDate(1); // going to 1st of the month
d.setHours(-1); // going to last hour before this date even started.
var lastMonthLastDate = d;
periods1.push(lastMonthLastDate.getFullYear()+"-"+(lastMonthLastDate.getMonth()+1)+"-"+lastMonthLastDate.getDate());
//go to last month first date
var lastMonthFirstDate = new Date(lastMonthLastDate.getFullYear(), lastMonthLastDate.getMonth(),1);
//for the remaining periods
for (var i=0;i<this.props.numberOfPeriods-1;i++) {
periods1.push(lastMonthFirstDate.getFullYear()+"-"+(lastMonthFirstDate.getMonth()+1)+"-"+lastMonthFirstDate.getDate());
lastMonthFirstDate=new Date(lastMonthFirstDate.getFullYear(), lastMonthFirstDate.getMonth()-1,1);
}
}
console.log(periods1); -->prints ["2017-12-31", "2016-1-1", "2015-1-1", "2014-1-1"]
this.setState((prevState)=>{
return {
periods: prevState.periods.push(periods1)
}
});
console.log(this.state.periods) --> prints []
}
render() {
return ( <div></div>)
}
How to get values in periods1 to periods state. I am trying to insert periods1 array into state periods array. Those are strings. Pls suggest where the error might be.