Vivekraj K R
Vivekraj K R

Reputation: 2548

Next.js - new Date() constructor throwing console errors

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!

Upvotes: 4

Views: 4485

Answers (3)

David
David

Reputation: 543

To fix hydration warnings, see the docs. Using useEffect is one option, which might not be viable in all cases.

https://nextjs.org/docs/messages/react-hydration-error

You can also disable SSR on a component level OR surpress the warning on the element.

e.g.

<td className="font-bold" suppressHydrationWarning>{`${dateTime.toLocaleTimeString()}`}</td>

Upvotes: 0

Vivekraj K R
Vivekraj K R

Reputation: 2548

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);

Upvotes: 11

Ani Chukwuebuka
Ani Chukwuebuka

Reputation: 1

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

Upvotes: -1

Related Questions