I am using DateRangePicker to get the date ranges and append the date to the api to get the latest dates data.
As in below code i can get updated state outside the EventHandler function but not inside it. I am getting the same date which is selected for the first time.
import React, { useState } from "react";
import DateRangePicker from "react-bootstrap-daterangepicker";
import "bootstrap-daterangepicker/daterangepicker.css";
import moment from "moment";
import DataProvider from "context/DataContext";
import ApiService from "services/api";
export default function DatePicker() {
const [fromDate, setFromDate] = useState(new Date());
const [toDate, setToDate] = useState(new Date());
const range = {
Today: [moment(), moment()],
Yesterday: [moment().subtract(1, "days"), moment().subtract(1, "days")],
"Last 7 Days": [moment().subtract(6, "days"), moment()],
"Last 30 Days": [moment().subtract(29, "days"), moment()],
"This Month": [moment().startOf("month"), moment().endOf("month")],
"Last Month": [
moment().subtract(1, "month").startOf("month"),
moment().subtract(1, "month").endOf("month"),
],
"Last Year": [
moment().subtract(1, "year").startOf("year"),
moment().subtract(1, "year").endOf("year"),
],
};
var startdate = moment(fromDate).format("yyyy-MM-DD");
var enddate = moment(toDate).format("yyyy-MM-DD");
console.log(startdate);
const handleEvent = (event, picker) => {
setFromDate(picker.startDate._d);
setToDate(picker.endDate._d);
console.log(startdate);
var requestData = {
metrics: ["views"],
project_id: "abc",
date_range: { start_at: fromDate, end_at: toDate },
};
ApiService.create({ requestData }).then((onSuccess) => {
console.log(onSuccess);
});
};
return (
<DateRangePicker
ranges={range}
alwaysShowCalendars={false}
onEvent={handleEvent}
>
<button>
{moment(fromDate).format("ll")} to {moment(toDate).format("ll")}
</button>
</DateRangePicker>
);
}
In requestData object you should change fromDate to picker.startDate._d, same on the other one toDate->endDate._d