date-fns/formatDistanceToNow return 'Invalid time value'

Viewed 18

I got error: 'Invalid time value' when using formatDistanceToNow from data-fns.

  • post.createdAt date format: 2022-09-10T18:12:10.072Z

Here is my code:

import formatDistanceToNow from 'date-fns/formatDistanceToNow'

export const SinglePost = () => {
  const { id } = useParams()
  const [post, setPost] = useState({})

  useEffect(() => {
    const fetchPost = async () => {
      const response = await fetch(`/api/posts/${id}`)
      const data = await response.json()

      if (response.ok) {
        setPost(data)
      }
    }

    fetchPost()
  }, [])

  return (
    <Flexbox >
      <SinglePostStyle className='flex-item'>
        <h1 className='post-title'>{post.title}</h1>
        <p className="post-author">By: {post.author}</p>

        // Invalid time value
        <p className="post-date">{formatDistanceToNow(new Date(post.createdAt))}</p>

        <img className='post-image' src={post.image} alt="" />
        <p className='post-description'>{post.description}</p>
      </SinglePostStyle>
      <Sidebar className='flex-item' />
    </Flexbox >
  )
}

if you have any suggestion please let me know, thanks

0 Answers
Related