How do you pass `Date` data from `getStaticProps` onto the component without serialization errors?
Answered
Transvaal lion posted this in #help-forum
Transvaal lionOP
I'm trying to simulate what I would get from a Database with this following code and I ran into an issue:
I keep getting a
error:
It is only when I added the
that it stopped giving me this error.
I then have to reformat it as
Should I just add the date format once I get the parameters from the
I keep getting a
cannot be serialized as JSON error on my code:export const getStaticProps = async () => {
const arr = await [{
title: "Title of the blog",
date: new Date("April 9, 2020"),
content: "Lorem ipsum dolor sit amet consectetur. Fermentum sollicitudin sit dictum quis. Sit tempor sit amet etiam lectus suspendisse quisque egestas. Augue netus eget eros aliquam egestas eget. Enim nisi varius integer odio adipiscing quis viverra. Turpis turpis viverra magnis bibendum. Proin pulvinar vitae sagittis non bibendum risus. Risus ac arcu malesuada hac fringilla integer. Quam sed vulputate est tincidunt et morbi imperdiet volutpat egestas. Vitae interdum varius adipiscing quis integer interdum venenatis amet egestas."
}
]
return {
props: {
arr
}
}
}error:
Error serializing .arr[0].date returned fromgetStaticPropsin "/Blogs".Reason:object("[object Date]") cannot be serialized as JSON. Please only return JSON serializable data types.It is only when I added the
.toJSON() method todate: new Date("April 9, 2020").toJSON();that it stopped giving me this error.
I then have to reformat it as
Date again once I get the parameter from the component by adding new Date:const BlogEdit = ({ arr }: { arr: { title: string, date: Date, content: string }[] }) => {
console.log(new Date(arr[0].date).getDate())
//code
}Should I just add the date format once I get the parameters from the
getStaticProps function? I'm not sure if I'm doing this the correct way. All I want is to use the separate Date methods getDate(), getFullYear(), getMonth().Answered by Ray
I usually turn the date to string and
new Date(date) in the component6 Replies
or use this plugin https://github.com/blitz-js/next-superjson-plugin
@Ray I usually turn the date to string and `new Date(date)` in the component
Transvaal lionOP
It makes perfect sense to format it in the component to avoid issues with the
getStaticProps or getServerSideProps functions. I remember reading about this plug in. I think we're both doing it right, but there's no guideline for coding on some things. Lol@Ray or use this plugin https://github.com/blitz-js/next-superjson-plugin
Transvaal lionOP
I tried using this plugin, but I still get serializing errors.