Home > Software design >  Next.js - new Date() constructor throwing console errors
Next.js - new Date() constructor throwing console errors

Time:07-17

I'm trying to use new Date() constructor in Next.js react component. But its throwing below console errors on production.

This is how I'm using the date constructor.

date: "2022-06-21T18:30:00.000Z"

{new Date(date).toLocaleDateString("en-US")}

Uncaught Error: Minified React error #425; - https://reactjs.org/docs/error-decoder.html?invariant=425
Uncaught Error: Minified React error #418; - https://reactjs.org/docs/error-decoder.html?invariant=418
Uncaught Error: Minified React error #423; - https://reactjs.org/docs/error-decoder.html?invariant=423

Any idea why its happening. Helps would be appreciated. Thanks!

CodePudding user response:

Is your “date” a variable on its own or is it a property of an object. If it is a variable, you should do “date = “ and not “date:” , if it is a property of an object, you should do “new Date(object.date)” . Replace object with the name of your object

CodePudding user response:

As per @bcjohn's comment I have figured out that hydration errors can be fixed by formatting the date in useEffect instead of directly adding it in jsx.

Here's the custom hook that I written for formatted date.

import { useState, useEffect } from "react";

const useFormattedDate = (date) => {
  const [formattedDate, setFormattedDate] = useState(null);

  useEffect(
    () => setFormattedDate(new Date(date).toLocaleDateString("en-US")),
    []
  );

  return formattedDate;
};

export default useFormattedDate;

Sample usage

const date = useFormattedDate(obj.date);
  • Related