简体   繁体   中英

RangeError: locale must contain formatDistance property when using locale variable in Next.js with date-fns

I have a website with multiple languages done in Next.js. Next.js provides several methods to get all the locales, here are the following:

{locale} // current locale in use 'es'
{locales} // all the configured locales in an array [ "en", "de", "es", "ja", "ru" ]
{defaultLocale} // if no locale provided, will use en

Then in my code, i have this date-fns method to get the distance in days for a given date i get from my createdAt value.

// my import languages
import { es, de, ja, en, ru } from 'date-fns/locale';


<BodyOne>
  This category was funded{' '}
  {formatDistance(new Date(category.createdAt), new Date(), {
    locale: locale,
    })}
</BodyOne>

This gives me the following error:

RangeError: locale must contain formatDistance property

I don't understand why, this works:

{
  locale: es,
   })}

But this one with the variable locale doesn't.

{
  locale: locale,
   })}

if I create a new constant, let's say:

const myCurrentLang = es;

it works, but if I output:

const myCurrentLang = 'es';

I get the error: RangeError: locale must contain formatDistance property

Maybe i need to convert the 'es' value to other type in order to make date-fns work.

the thing is formatDistance is waiting for a namespace and you're trying to send a string as a parameter. When you declared const myCurrentLang = es; it works because es is referring to date-fns/locale's namespace...

Hope it helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM