umami/hooks/useDateRange.js

44 lines
1.4 KiB
JavaScript
Raw Normal View History

import { useDispatch, useSelector } from 'react-redux';
import { parseISO } from 'date-fns';
2020-09-01 00:02:32 +02:00
import { getDateRange } from 'lib/date';
import { getItem, setItem } from 'lib/web';
import { setDateRange } from '../redux/actions/websites';
import { DATE_RANGE_CONFIG, DEFAULT_DATE_RANGE } from 'lib/constants';
import useForceUpdate from './useForceUpdate';
import useLocale from './useLocale';
2020-09-01 00:02:32 +02:00
export default function useDateRange(websiteId, defaultDateRange = DEFAULT_DATE_RANGE) {
const dispatch = useDispatch();
const { locale } = useLocale();
const dateRange = useSelector(state => state.websites[websiteId]?.dateRange);
const forceUpdate = useForceUpdate();
const globalDefault = getItem(DATE_RANGE_CONFIG);
let globalDateRange;
if (globalDefault) {
if (typeof globalDefault === 'string') {
globalDateRange = getDateRange(globalDefault, locale);
} else if (typeof globalDefault === 'object') {
globalDateRange = {
...globalDefault,
startDate: parseISO(globalDefault.startDate),
endDate: parseISO(globalDefault.endDate),
};
}
}
function saveDateRange(values) {
const { value } = values;
if (websiteId) {
dispatch(setDateRange(websiteId, values));
} else {
setItem(DATE_RANGE_CONFIG, value === 'custom' ? values : value);
forceUpdate();
}
}
return [dateRange || globalDateRange || getDateRange(defaultDateRange, locale), saveDateRange];
2020-09-01 00:02:32 +02:00
}