Skip to content

Instantly share code, notes, and snippets.

@crisu83
Last active December 21, 2020 15:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save crisu83/b9da935d885c148e23fc97da8c911633 to your computer and use it in GitHub Desktop.
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.
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