I have a component in which I am trying to fetch the values of sensors based on the time, I was able to get the sensors based on the regular date format, however I have another option where I want it so that the user can get the data based on the month instead of a particular date, However I am not able to do so.
This is my component and functions :
const History = (props) => {
const params = useParams();
const sensorId = params.sensorId;
const facilityId = params.facilityId;
const [zeroFilter, setZeroFilter] = React.useState(true);
const [history, setHistory] = React.useState([]);
const displayHistory = history.filter((x) =>
zeroFilter ? x.value !== 0 : true
);
const [date, setDate] = React.useState(null);
const [month, setMonth] = React.useState(null);
const [loading, setLoading] = React.useState(true);
const language = props.language;
const download = () => {
let csvString = "Value,Date\n";
let csvStringMonth = "Value,Month\n"
csvString += displayHistory
.map(
(x) =>
`${x.value},${moment(x.createdAt.seconds * 1000).format(
"YYYY-MM-DD HH:mm:ss"
)}`
)
.join("\n");
const file_name = `${facilityId}_${sensorId}.csv`;
csvStringMonth += displayHistory.map(
(x) =>
`${x.value},${moment(x.createdAt.seconds * 1000).format(
"YYYY-MM-DD HH:mm:ss"
)}`
)
.join("\n");
//CSVのバイナリデータを作る
let blob = new Blob([csvString], { type: "text/csv" });
let uri = URL.createObjectURL(blob);
// //リンクタグを作る
let link = document.createElement("a");
link.download = file_name;
link.href = uri;
// //作ったリンクタグをクリックさせる
document.body.appendChild(link);
link.click();
// //クリックしたら即リンクタグを消す
document.body.removeChild(link);
};
const changeDate = (newDate) => {
setDate(newDate);
getData(newDate);
};
const changeMonth = (newMonth) => {
setMonth(newMonth);
getDataMonth(newMonth);
};
const resetDate = () => {
setDate(null);
setMonth(null)
getData();
getDataMonth();
};
**const getDataMonth = (targetMonth) => {
setLoading(true);
// Calculate start and end dates for the selected month
const startOfMonth = dayjs(targetMonth).startOf("month");
const endOfMonth = dayjs(targetMonth).endOf("month");
const q = query(
collection(db, ENV, VERSION, "facilities", facilityId, "sensorHistory"),
orderBy("createdAt", "desc"),
where("deviceId", "==", sensorId),
where("dataType", "==", "data"),
where("createdAt", ">=", startOfMonth.toDate()),
where("createdAt", "<=", endOfMonth.toDate())
);
getDocs(q)
.then((querysnapshot) => {
setLoading(false);
setHistory(
querysnapshot.docs.map((doc) => {
return { ...doc.data(), id: doc.id };
})
);
})
.catch((e) => {
alert("Error fetching data!");
setLoading(false);
console.error(e);
});
};
**
const getData = (targetDate) => {
setLoading(true);
let q;
if (targetDate) {
const start = targetDate.startOf("day").toDate();
const end = targetDate.add(1, "d").startOf("day").toDate();
q = query(collection(db, ENV, VERSION, "facilities", facilityId, "sensorHistory"),
orderBy("createdAt", "desc"),
where("deviceId", "==", sensorId),
where("dataType", "==", "data"),
where("createdAt", ">=", start),
where("createdAt", "<", end)
);
} else {
q = query(collection(db, ENV, VERSION, "facilities", facilityId, "sensorHistory"),
orderBy("createdAt", "desc"),
where("deviceId", "==", sensorId),
limit(100),
where("dataType", "==", "data")
);
}
getDocs(q)
.then((querysnapshot) => {
setLoading(false);
setHistory(
querysnapshot.docs.map((doc) => {
return { ...doc.data(), id: doc.id };
})
);
})
.catch((e) => {
alert("!!!");
setLoading(false);
console.error(e);
});
};
React.useEffect(() => {
getData();
getDataMonth()
}, []);
React.useEffect(() => {
dayjs.locale(language);
}, [language]);
return (
<>
<Stack
spacing={1}
direction="row"
justifyContent="flex-end"
alignItems="center"
>
<Button variant="outlined" onClick={resetDate}>
{BasicLanguage.sensor.recent[language]}
</Button>
<LocalizationProvider
dateAdapter={AdapterDayjs}
adapterLocale={language}
>
<DatePicker
disableFuture={true}
value={date}
onChange={changeDate}
format={BasicLanguage.common.date.datePicker.long[language]}
/>
</LocalizationProvider>
</Stack>
<TableContainer
sx={{
mt: 2,
maxHeight: "400px",
"& .MuiTableCell-head": {
backgroundColor: "rgba(220,220,220,1)",
fontWeight: "bold",
},
}}
>
<Table stickyHeader>
<TableHead>
<TableRow>
<TableCell>{BasicLanguage.sensor.value[language]}</TableCell>
<TableCell>{BasicLanguage.sensor.date[language]}</TableCell>
</TableRow>
</TableHead>
<TableBody>
{loading ? (
<TableRow>
<TableCell colSpan={2}>
<Box
sx={{
display: "flex",
height: 200,
justifyContent: "center",
alignItems: "center",
}}
>
<CircularProgress />
</Box>
</TableCell>
</TableRow>
) : (
//history table showing list of sensors in relation to the date selected
displayHistory.map((x) => {
return (
<TableRow key={x.id}>
<TableCell>{x.value}</TableCell>
<TableCell>
{moment(x.createdAt.seconds * 1000).format(
"YYYY-MM-DD HH:mm:ss"
)}
</TableCell>
</TableRow>
);
})
)}
{ }
</TableBody>
</Table>
</TableContainer>
<Stack direction="row" justifyContent="space-between" sx={{ mt: 2 }}>
<Box >
{history.length > 0 ? (
<Button onClick={download} variant="outlined" size="medium" sx={{ mr: '2rem', height: "full", width: "full" }} >
{BasicLanguage.common.download[language]}
</Button>
) : (
<></>
)}
<FormControlLabel
control={
<Checkbox
checked={zeroFilter}
onChange={(e) => setZeroFilter(e.target.checked)}
/>
}
label={BasicLanguage.sensor.zero[language]}
/>
</Box>
<Box>
<LocalizationProvider
dateAdapter={AdapterDayjs}
adapterLocale={language}
>
//for month and year selection
<DatePicker
disableFuture={true}
onChange={(newValue) => {
if (newValue instanceof Date) {
const selectedMonth = newValue.getMonth();
changeMonth(selectedMonth); // Pass the selected month to the getData function
} else {
console.error("Invalid date format:", newValue);
}
}}
sx={{ padding: "0px", outline: "none" }}
label={BasicLanguage.users.activityReport.date.format[language]}
value={month} // Use the month state as the value
views={['month', 'year']} />
</LocalizationProvider>
</Box>
</Stack >
</>
);
};
I made changes in the query in order to fetch the data based on month, however I have an error that seems to be a problem of date format and I dont know what to do. I searched a lot on google if there was any example to fetch the data based off on month and year but was not able to find any.