|
| 1 | +import { DateTime } from 'luxon'; |
| 2 | +import { useCallback, useEffect, useMemo, useState } from 'react'; |
| 3 | +import { QueryParameterName, useUrlQuery } from './useUrlQuery'; |
| 4 | + |
| 5 | +interface Props { |
| 6 | + initialize?: boolean; |
| 7 | + queryParamName: QueryParameterName; |
| 8 | +} |
| 9 | + |
| 10 | +/** |
| 11 | + * Query parameter hook for setting and getting date query parameter. Initialization |
| 12 | + * of this query parameter can be set to false if you don't want to initialize it. |
| 13 | + * TODO: This is currently partly copypasted from useObservationDateQueryParam, and |
| 14 | + * these could maybe be combined at least from some parts. |
| 15 | + */ |
| 16 | +export const useDateQueryParam = ({ |
| 17 | + initialize = true, |
| 18 | + queryParamName, |
| 19 | +}: Props) => { |
| 20 | + const { getDateTimeFromUrlQuery, setDateTimeToUrlQuery, queryParams } = |
| 21 | + useUrlQuery(); |
| 22 | + |
| 23 | + const [defaultDate] = useState(DateTime.now().startOf('day')); |
| 24 | + |
| 25 | + /** |
| 26 | + * Sets date to URL query |
| 27 | + * replace flag can be given to replace the earlier url query instead |
| 28 | + * of pushing it. This affects how the back button or history.back() works. |
| 29 | + * If the history is replaced, it means that back button will not go to the |
| 30 | + * url which was replaced, but rather the one before it. |
| 31 | + */ |
| 32 | + const setDateToUrl = (date: DateTime, replace = false) => { |
| 33 | + setDateTimeToUrlQuery( |
| 34 | + { paramName: queryParamName, value: date }, |
| 35 | + { replace }, |
| 36 | + ); |
| 37 | + }; |
| 38 | + |
| 39 | + // Memoize the actual value to prevent unnecessary updates |
| 40 | + const date = useMemo(() => { |
| 41 | + try { |
| 42 | + return getDateTimeFromUrlQuery(queryParamName) || defaultDate; |
| 43 | + } catch { |
| 44 | + // If parsing date fails, set default date |
| 45 | + setDateToUrl(defaultDate, true); |
| 46 | + return defaultDate; |
| 47 | + } |
| 48 | + // eslint-disable-next-line react-hooks/exhaustive-deps |
| 49 | + }, [defaultDate, getDateTimeFromUrlQuery]); |
| 50 | + |
| 51 | + /** Determines and sets date to query parameters if it's not there */ |
| 52 | + const initializeDate = useCallback(async () => { |
| 53 | + if (!queryParams[queryParamName] || !date) { |
| 54 | + setDateToUrl(defaultDate, true); |
| 55 | + } |
| 56 | + // eslint-disable-next-line react-hooks/exhaustive-deps |
| 57 | + }, [defaultDate, date, queryParams[queryParamName]]); |
| 58 | + |
| 59 | + useEffect(() => { |
| 60 | + if (initialize) { |
| 61 | + initializeDate(); |
| 62 | + } |
| 63 | + }, [initialize, initializeDate, queryParams]); |
| 64 | + |
| 65 | + return { |
| 66 | + date, |
| 67 | + setDateToUrl, |
| 68 | + }; |
| 69 | +}; |
0 commit comments