Last active
December 21, 2020 15:03
-
-
Save crisu83/b9da935d885c148e23fc97da8c911633 to your computer and use it in GitHub Desktop.
A custom date formatting hook for date-fns in next.js apps written in TypeScript.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { | |
format, | |
formatDistance, | |
formatDistanceStrict, | |
formatRelative, | |
} from 'date-fns'; | |
import {useRouter} from 'next/router'; | |
import {useEffect, useState} from 'react'; | |
const noop = () => {}; | |
type LocalizedDateFn<T> = (locale?: Locale) => T; | |
// TODO: Figure out why `format` has to be cast to `any` to avoid a ts(2349) error. | |
const localizedFormat: LocalizedDateFn<typeof format> = locale => ( | |
date, | |
format, | |
options = {} | |
) => (format as any)(date, format, {...options, locale}); | |
const localizedFormatDistance: LocalizedDateFn< | |
typeof formatDistance | |
> = locale => (date, baseDate, options = {}) => | |
formatDistanceStrict(date, baseDate, {...options, locale}); | |
const localizedFormatDistanceStrict: LocalizedDateFn< | |
typeof formatDistanceStrict | |
> = locale => (date, baseDate, options = {}) => | |
formatDistanceStrict(date, baseDate, {...options, locale}); | |
const localizedFormatRelative: LocalizedDateFn< | |
typeof formatRelative | |
> = locale => (date, baseDate, options = {}) => | |
formatRelative(date, baseDate, {...options, locale}); | |
export function useDateFormatting() { | |
const {defaultLocale, locale} = useRouter(); | |
const [loading, setLoading] = useState(true); | |
const [dateFnsLocale, setDateFnsLocale] = useState<Locale>(undefined); | |
useEffect(() => { | |
const importLocale = async () => { | |
const dateFnsLocales = await import('date-fns/locale'); | |
setDateFnsLocale(dateFnsLocales[locale]); | |
}; | |
locale !== defaultLocale | |
? importLocale().then(() => setLoading(false)) | |
: setLoading(false); | |
}, [defaultLocale, locale]); | |
return { | |
format: !loading ? localizedFormat(dateFnsLocale) : noop, | |
formatDistance: !loading ? localizedFormatDistance(dateFnsLocale) : noop, | |
formatDistanceStrict: !loading | |
? localizedFormatDistanceStrict(dateFnsLocale) | |
: noop, | |
formatRelative: !loading ? localizedFormatRelative(dateFnsLocale) : noop, | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment